使用MahAppsMetro ProgressIndicator绑定失败

时间:2013-08-14 19:43:01

标签: c# wpf binding mahapps.metro

我必须关注ProgressIndicator

<MahAppsControls:ProgressIndicator Width="100"
                                   Height="10"
                                   VerticalAlignment="Center"
                                   ProgressColour="White" 
                                   Visibility="{Binding ProgressVisibility}"/>

并且在ViewModel中与此View相关,我实现了

private Visibility progressVisibility = Visibility.Collapsed;
public Visibility ProgressVisibility
{
    get { return progressVisibility; }
    set
    {
        if (value == progressVisibility)
            return;
        progressVisibility = value;
        this.OnPropertyChanged("ProgressVisibility");
    }
}

问题是这种绑定失败了,我不知道为什么。使用Snoop我有以下

  

System.Windows.Data错误:40:BindingExpression路径错误:'object'''ProgressIndicator'(Name ='progressIndicator')'上找不到'ProgressVisibility'属性。 BindingExpression:路径= ProgressVisibility; DataItem ='ProgressIndicator'(Name ='progressIndicator');

     

目标元素是'ProgressIndicator'(Name ='progressIndicator');目标属性是“可见性”(类型“可见性”)   System.Windows.Data错误:40:BindingExpression路径错误:在'object'''ProgressIndicator'(Name ='progressIndicator')'上找不到'ProgressVisibility'属性。 BindingExpression:路径= ProgressVisibility; DataItem ='ProgressIndicator'(Name ='progressIndicator');

     

目标元素是'ProgressIndicator'(Name ='progressIndicator');目标属性是“可见性”(类型“可见性”)   System.Windows.Data错误:40:BindingExpression路径错误:在'object'''ProgressIndicator'(Name ='progressIndicator')'上找不到'ProgressVisibility'属性。 BindingExpression:路径= ProgressVisibility; DataItem ='ProgressIndicator'(Name ='progressIndicator');

     

目标元素是'ProgressIndicator'(Name ='progressIndicator');目标属性是“可见性”(类型“可见性”)

我感谢有绑定错误,但是我通过

在App.xaml.cs中设置主窗口DataContext
MainWindow window = new MainWindow();
MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();

// When the ViewModel asks to be closed, close the window.
EventHandler handler = null;
handler = delegate
{
    mainWindowViewModel.RequestClose -= handler;
    window.Close();
};
mainWindowViewModel.RequestClose += handler;

// Allow all controls in the window to bind to the ViewModel by setting the 
// DataContext, which propagates down the element tree.
window.DataContext = mainWindowViewModel;
window.Show();

那么,为什么绑定失败?

感谢您的时间。

1 个答案:

答案 0 :(得分:7)

问题是MahApps.ProgressIndicator控件中的错误。

如果查看source code,您会发现它会覆盖DataContext自身:

public ProgressIndicator()
{
        InitializeComponent();
        this.DataContext = this;

因此,您需要通过直接绑定到元素名称来解决此(愚蠢)限制,从而有效避免使用普通数据绑定。

例如,如果您命名Window(在xaml中),即:

<Window ...
    Name="Self">
    <!--...

你可以这样做:

<MahAppsControls:ProgressIndicator Width="100"
                               Height="10"
                               VerticalAlignment="Center"
                               ProgressColour="White" 
                               Visibility="{Binding ElementName=Self, Path=DataContext.ProgressVisibility}"/>