WPF bool依赖属性C#

时间:2016-01-22 15:51:04

标签: c# wpf

如何创建简单的bool依赖属性IsInput。在代码中创建类时,此值只能设置为truefalse。看起来相当简单,但我在网上搜索,并没有找到一个明确的例子。

我已经在网上看到了类似这样的例子但是我不太清楚我要复制什么来正确创建我自己的bool依赖属性。

public static readonly DependencyProperty AncestorProperty =
    DependencyProperty.Register("Ancestor", typeof(FrameworkElement), typeof(MyItem),
        new FrameworkPropertyMetadata(Ancestor_PropertyChanged));

/// <summary>
/// Event raised when 'Ancestor' property has changed.
/// </summary>
private static void Ancestor_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    MyItem c = (MyItem)d;
    c.UpdateHotspot();
}

1 个答案:

答案 0 :(得分:2)

Register方法的第二个参数是属性的类型,即bool,而第三个参数是所谓的所有者类型,它是声明属性(下例中的MyControl)。

对于完整的依赖属性声明,您还需要声明&#34;包装器&#34;具有getter和setter的属性,该属性调用依赖属性的GetValueSetValue方法。

public static readonly DependencyProperty IsInputProperty =
    DependencyProperty.Register("IsInput", typeof(bool), typeof(MyControl),
        new FrameworkPropertyMetadata(IsInputPropertyChanged));

/// <summary>
/// CLR wrapper for the 'IsInput' dependency property.
/// </summary>
public bool IsInput
{
    get { return (bool)GetValue(IsInputProperty); }
    set { SetValue(IsInputProperty, value); }
}

/// <summary>
/// Callback called when 'IsInput' property has changed.
/// </summary>
private static void IsInputPropertyChanged(
    DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    bool b = (bool)e.NewValue;
    //TODO
}