【发布时间】:2015-09-30 21:11:47
【问题描述】:
我有一个带有单个 DependencyProperty 的简单用户控件。我无法在此属性上设置绑定。我没有得到任何异常,但绑定消失了。
我看不出这里出了什么问题。就是这么简单。
这是我的用户控件:
XAML:
<UserControl x:Class="Test.Controls.SimpleUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="ucThis">
<TextBox Text="{Binding Path=MyString, ElementName=ucThis}" />
</UserControl>
代码:
public partial class SimpleUserControl : UserControl
{
public SimpleUserControl()
{
InitializeComponent();
}
public string MyString
{
get { return (string)GetValue(MyStringProperty); }
set { SetValue(MyStringProperty, value); }
}
public static readonly DependencyProperty MyStringProperty =
DependencyProperty.Register("MyString", typeof(string),
typeof(SimpleUserControl), new UIPropertyMetadata("simple user control"));
}
来自测试应用的 XAML:
<StackPanel>
<testControls:SimpleUserControl MyString="{Binding Path=TestString}"
x:Name="simpleUC" />
<Label Content="From control" />
<Border Margin="5"
BorderBrush="Black"
BorderThickness="1"
Visibility="{Binding Path=MyString, ElementName=simpleUC, Converter={StaticResource nullVisConv}}">
<ContentPresenter Content="{Binding Path=MyString, ElementName=simpleUC}" />
</Border>
<TextBlock Text="Value from control is null."
Margin="5"
Visibility="{Binding Path=MyString, ElementName=simpleUC, Converter={StaticResource nullVisConv}, ConverterParameter={custom:BooleanValue Value=True}}" />
<Label Content="From binding" />
<Border Margin="5"
BorderBrush="Black"
BorderThickness="1"
Visibility="{Binding Path=TestString, Converter={StaticResource nullVisConv}}">
<ContentPresenter Content="{Binding Path=TestString}" />
</Border>
<TextBlock Text="Value from binding is null."
Margin="5"
Visibility="{Binding Path=TestString, Converter={StaticResource nullVisConv}, ConverterParameter={custom:BooleanValue Value=True}}" />
<TextBox Text="You can set focus here." />
</StackPanel>
测试应用的主窗口有一个名为TestString 的属性,是它自己的DataContext 并正确实现INotifyPropertyChanged。 SimpleUserControl.MyString 会更新,但它绑定到的属性 (TestString) 不会。我已经用 Snoop 进行了检查;我在SimplerUserControl 上设置的绑定在运行时不存在。这里发生了什么?
更新
好的。因此,如果我指定 Mode=TwoWay 绑定有效。那太棒了。谁能向我解释为什么它会这样?
谢谢。
【问题讨论】:
-
它是
Mode=TwoWay。该死的。 -
你找到了太好了 :)
标签: wpf data-binding user-controls