小编Oli*_*ver的帖子

XAML绑定不依赖于依赖属性?

我正在尝试(并且失败)在xaml中对依赖项属性进行数据绑定.当我使用代码后,它工作正常,但不是在xaml中.

用户控件只是一个TextBlock绑定到依赖属性的控件:

<UserControl x:Class="WpfTest.MyControl" [...]>
     <TextBlock Text="{Binding Test}" />
</UserControl>
Run Code Online (Sandbox Code Playgroud)

而dependency属性是一个简单的字符串:

public static readonly DependencyProperty TestProperty 
= DependencyProperty.Register("Test", typeof(string), typeof(MyControl), new PropertyMetadata("DEFAULT"));

public string Test
{
    get { return (string)GetValue(TestProperty); }
    set { SetValue(TestProperty, value); }
}
Run Code Online (Sandbox Code Playgroud)

我有一个常规属性与INotifyPropertyChanged主窗口中的常规实现.

private string _myText = "default";
public string MyText
{
   get { return _myText; }
   set {  _myText = value; NotifyPropertyChanged(); }
}
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.如果我将此属性绑定到TextBlock主窗口上的一切,一切正常.如果MyText更改和所有内容都在世界范围内,则文本会正确更新.

<TextBlock Text="{Binding MyText}" />
Run Code Online (Sandbox Code Playgroud)

但是,如果我在用户控件上执行相同的操作,则不会发生任何事情.

<local:MyControl x:Name="TheControl" Test="{Binding MyText}" />
Run Code Online (Sandbox Code Playgroud)

现在有趣的是,如果我在代码背后执行相同的绑定,它就可以了! …

c# data-binding wpf xaml dependency-properties

5
推荐指数
1
解决办法
6207
查看次数

标签 统计

c# ×1

data-binding ×1

dependency-properties ×1

wpf ×1

xaml ×1