我的Dependency属性只有一种绑定方式

本文关键字:一种 绑定 方式 Dependency 属性 我的 | 更新日期: 2023-09-27 18:06:47

我是WPF的新手,我正在做一些我觉得非常直接的事情。我创建了一个包含文本框的UserControl,我想绑定这个文本框。Text属性转换为我的用户控件的依赖属性Value。文本框将正确显示"值",如果更改"值"的值,文本框将相应地更新。但是,如果我更改文本框中的值,则值不会更改以反映它。即使我手动将绑定模式设置为双向,它仍然只能绑定单向。我把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 Whatever}"在XAML中赋值任何建议或帮助将不胜感激。谢谢你。

我的Dependency属性只有一种绑定方式

您需要将Text绑定的UpdateSourceTrigger设置为PropertyChanged。TextBox的默认值是LostFocus。如果这是窗口中唯一的控件,那么就没有其他任何东西可以接收焦点,因此LostFocus事件永远不会触发,绑定也永远不会更新源。

<TextBox x:Name="TextForm" Text="{Binding Path=Value, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />