c# - 如何在 UserControl 中使用绑定(bind)的 XAML 属性?

标签 c# xaml windows-phone-8.1 uwp

我有自己的UserControl

 <local:MyUserControl MyProperty="{Binding myString}"/>                                      

我正在将 myString 绑定(bind)到它。现在我想在我的 UserControl 中使用它。我在我的 UserControl 中定义了 DependencyProperty:

    public string MyProperty
    {
        get { return (string)GetValue(MyPropertyProperty); }
        set
        {
            Debug.WriteLine(value);//writes nothing, null
            SetValue(MyPropertyProperty, value);
        }
    }
    public static readonly DependencyProperty MyPropertyProperty =
      DependencyProperty.Register("MyProperty", typeof(string), typeof(MyUserControl), new PropertyMetadata(null));

我做错了什么?我想用这个字符串做一些事情。但它始终为空。

最佳答案

Debug.WriteLine(value);不写入任何内容不是因为值为 null 。使用 {Binding} 时,不保证依赖属性的 getter 和 setter 能够运行,您的属性(property)的设置者不会被调用。您可以在setter中添加断点来测试它。

请注意Custom dependency properties中的以下警告:

In all but exceptional circumstances, your wrapper implementations should perform only the GetValue and SetValue operations. Otherwise, you'll get different behavior when your property is set via XAML versus when it is set via code. For efficiency, the XAML parser bypasses wrappers when setting dependency properties; whenever possible, it uses the registry of dependency properties.

您可以在对DependencyProperty.Register的原始调用中添加属性更改处理程序,而不是在属性的 setter 中使用react。在此处理程序中,您可以对新值进行操作。例如:

public string MyProperty
{
    get { return (string)GetValue(MyPropertyProperty); }
    set
    {
        SetValue(MyPropertyProperty, value);
    }
}

public static readonly DependencyProperty MyPropertyProperty =
  DependencyProperty.Register("MyProperty", typeof(string), typeof(MyUserControl), new PropertyMetadata(null, OnPropertyChanged));

private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if ((string)e.NewValue != (string)e.OldValue)
    {
        Debug.WriteLine(e.NewValue);
    }
}

如果您想在 UserControl 中使用绑定(bind)字符串,您可以使用MyProperty UserControl的。例如:

在您的 UserControl 中:

<UserControl Name="root" ...>
    <StackPanel>
        <TextBlock Text="{Binding MyProperty, ElementName=root}" />
    </StackPanel>
</UserControl> 

然后当你使用<local:MyUserControl MyProperty="{Binding myString}"/>时,你的UserControl将显示 myString 的值.

关于c# - 如何在 UserControl 中使用绑定(bind)的 XAML 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34033198/

相关文章:

c# - ASP.Net MVC C# AutoMapper 使用 Where 语句

c# - 未检测到 C# 中的条形码

c# - 如何使用 Xamarin.Forms 中的转换器将文本转换为颜色?

xaml - Metro XAML - TemplateBinding 和 SolidColorBrush 的问题

c# - 在 mediaElement 中设置位置(WP8.1 中的 ScrubbingEnabled 替代方案)

c# - 在导航到 Page Windows Phone 8.1 后将项目异步加载到 ListView

c# - 如何创建有意义的动态属性?

xaml - 使用 XAML 和 C++/WinRT 时,IDL 中必须包含哪些属性/函数?

c# - Windows phone 8.1 Toast 带你到某个页面

c# - 如何将 xbf 文件添加到 visual studio 项目