用Binding对象填充的依赖属性?

时间:2017-09-13 18:20:27

标签: c# uwp

为什么以下用" Binding"填充我的依赖属性?对象而不是字符串值?

<local:CustomButton MyText="{Binding Name}" />

它适用于普通按钮。

这是我注册按钮属性的方式:

public static DependencyProperty RegisterProperty(string propertyName) {
    return DependencyProperty.Register(propertyName, typeof(object), typeof(ButtonHD), new PropertyMetadata(null));
}

其余的只是普通的样板代码。为什么在将名称绑定到MyText时获取Binding对象?我的意思是它适用于普通按钮,这意味着绑定很好。这非常奇怪。

完全实现我的用户控件:

public sealed partial class CustomButton : UserControl {
    public object MyText {
        get { return GetValue(MyTextDependency); }
        set { SetValue(MyTextDependency, value); }
    }

    public static readonly DependencyProperty MyTextDependency = RegisterProperty(nameof(MyText));

    public CustomButton() {
        InitializeComponent();
    }

    public void Render(CanvasControl sender, CanvasDrawEventArgs e) {
      var test = MyText;
      // The below fails:
      string test = (string) MyText;
    }

    public static DependencyProperty RegisterProperty(string propertyName) {
        return DependencyProperty.Register(propertyName, typeof(object), typeof(CustomButton), new PropertyMetadata(null));
    }
}

在这里我的XAML:

<Canvas:CanvasControl Background="Transparent" Draw="Render">
    <Interactivity:Interaction.Behaviors>
        <Core:EventTriggerBehavior EventName="PointerReleased">
            <Core:InvokeCommandAction Command="{Binding MyCommand}" />
        </Core:EventTriggerBehavior>
    </Interactivity:Interaction.Behaviors>
</Canvas:CanvasControl>

1 个答案:

答案 0 :(得分:-1)

如果您在旁边的某个地方使用MyText,则在检查时您的对象可能是空的,内部没有字符串,而是存在Binding表达式。 您可以分配一些默认值,并在DependencyPropertyChanged上添加一些操作,并验证故障位置。 样品:

var metadata = new FrameworkPropertyMetadata( "", OnValueChanged, null, null)
return DependencyProperty.Register(propertyName, typeof(object), 
                                   typeof(CustomButton), metadata)

private static void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
  ;
}