我是 WPF 新手,我正在做一些我觉得非常简单的事情。我创建了一个包含文本框的 UserControl,我想将 TextBox.Text 属性绑定(bind)到我的用户控件 Value 的依赖属性。文本框正确显示值,如果更改值的值,文本框也会相应更新。但是,如果我更改文本框中的值,值不会更改以反射(reflect)它。即使我手动将绑定(bind)模式设置为双向,它仍然只绑定(bind)一种方式。我将 Value 设置为依赖属性,所以这不应该解决问题吗?
这是我的 XAML(为了便于阅读,我删除了其他控件):
<UserControl x:Class="WindowsApp.FormBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WindowsApp">
<Grid DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=local:FormBox}}">
<TextBox x:Name="TextForm" Text="{Binding Path=Value, Mode=TwoWay}" />
</Grid>
</UserControl>
这是 C#,Visual Studio 自动为我生成了它,所以也许有什么不对劲
public String Value
{
get { return (String)GetValue(ValueProperty); }
set
{
SetValue(ValueProperty, value);
}
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(String), typeof(FormBox));
在代码的其他部分,我只是通过执行 Value="{Binding Everything}"
在 XAML 中分配 Value
任何建议或帮助将不胜感激。谢谢。
最佳答案
您需要将文本绑定(bind)的 UpdateSourceTrigger 设置为 PropertyChanged。 TextBox 的默认设置是 LostFocus。如果这是窗口中唯一的控件,则没有其他任何控件可以接收焦点,因此 LostFocus 事件永远不会触发,并且绑定(bind)永远不会更新源。
<TextBox x:Name="TextForm" Text="{Binding Path=Value, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
关于c# - 我的依赖属性仅以一种方式绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24027319/