这个异常是由依赖属性引起的吗?

时间:2014-06-23 10:02:03

标签: c# wpf xaml

我不明白为什么在运行应用程序时会出现此异常。

我在MainWindow类中创建了一个依赖属性,在ImagesGrid类中我调用了这个属性。

我没有对xaml做任何改动。我也应该在那里贴一些东西吗?

这是依赖性propoerty的代码:

 public Visibility ButtonVisible
        {
            get { return (Visibility)GetValue(ButtonVisibleProperty); }
            set { SetValue(ButtonVisibleProperty, value); }
        }

    public static readonly DependencyProperty ButtonVisibleProperty =
        DependencyProperty.Register("ButtonVisible", typeof(Visibility), typeof(MainWindow), new PropertyMetadata(false));

这是我打电话给

的地方
  if (selectedModel is WineGroupModel)
        {
            MainWindow winesWindow = new MainWindow(); //mainwindow
            winesWindow.ButtonVisible = System.Windows.Visibility.Hidden;
            //some code
        }

这是构造函数MainWindow

public MainWindow()
    {
        this.InitializeComponent();

        this.DataContext = this;

        ImagesDir = @".\GalleryImages";

    }

这是按钮的xaml代码:

<k:KinectCircleButton Style="{StaticResource BackButtonStyle}" Foreground="#511C74"  Name="BacKinectCircleButton"  Label=""></k:KinectCircleButton>

这是图片:

http://i60.tinypic.com/5zqt5.png

1 个答案:

答案 0 :(得分:1)

您已为该属性设置了错误的默认值,因为其类型为Visibility,而非bool

将声明更改为

public static readonly DependencyProperty ButtonVisibleProperty =
    DependencyProperty.Register(
        "ButtonVisible", typeof(Visibility), typeof(MainWindow),
        new PropertyMetadata(Visibility.Collapsed));

或完全省略属性元数据:

public static readonly DependencyProperty ButtonVisibleProperty =
    DependencyProperty.Register(
        "ButtonVisible", typeof(Visibility), typeof(MainWindow));

您可以将按钮的Visibility属性绑定到属性,如下所示:

<k:KinectCircleButton ... Visibility="{Binding Path=ButtonVisible,
    RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}" />