c# - 我的依赖属性仅以一种方式绑定(bind)

标签 c# wpf xaml data-binding

我是 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/

相关文章:

C# 应用程序在检索 youtube 请求时卡住

wpf - 多绑定(bind) StringFormat 中的换行符或回车符

c# - WPF MVVM : Calling a method in view model from a converter

c# - 如何将 2 个 CollectionViewSource 绑定(bind)到 GridView

WPF DataTrigger 适用于图像,但不适用于路径

属性表达式的 C# 聚合返回 AmbiguousMatchException

c# - sql server 2008 r2中的当前月份和年份

c# - 如何在 Silverlight C# for WP7 中使用 NavigationService 作为同步回调的结果?

c# - WPF 和外部 CSS 文件

silverlight - 如何在应用栏中集成枢轴控制?