0

所以我为我的 xaml 用户控件创建了一个 bool 依赖属性。但是,当该值在 xaml 中设置为 false 时,它​​不会在 xaml 中设置为 true 时触发事件。无论如何,我怎样才能让它触发事件?

public static readonly DependencyProperty AvailableProperty =
    DependencyProperty.Register("Available", typeof(bool), typeof(DetailPannel),
    new PropertyMetadata(null, onAvailablePropertyChanged));

public bool Available
{
    get { return (bool)GetValue(AvailableProperty);  }
    set { SetValue(AvailableProperty, value); }
}

private async static void onAvailablePropertyChanged(DependencyObject d,   DependencyPropertyChangedEventArgs e)
{
    var obj = d as DetailPannel;
    bool avaible = (bool.Parse(e.NewValue.ToString())); 
    if(avaible == false )
    {            
        obj.PreviewImage.Source = await ConvertToGreyscale(obj.PreviewImage);
        obj.StateRelatedImage.Source = new BitmapImage(new Uri("ms-appx:///icon.png")); 
    }
} 
4

1 回答 1

1

该值null对于 bool 属性无效。更改您的 PropertyMetadata 以指定falsetrue作为默认值:

public static readonly DependencyProperty AvailableProperty =
    DependencyProperty.Register("Available", typeof(bool), typeof(DetailPannel),
    new PropertyMetadata(false, onAvailablePropertyChanged));

您的 PropertyChanged 处理程序中的代码看起来也很可疑。不要使用bool.Parse,而只是e.NewValue转换为bool

private async static void onAvailablePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var obj = d as DetailPannel;
    var available = (bool)e.NewValue; 

    if (!available)
    {
        ...
    }
} 
于 2012-12-14T21:58:34.980 回答