简体   繁体   English

双向绑定WPF

[英]Two-way binding in WPF

I cannot get a two-way bind in WPF to work.我无法在 WPF 中进行双向绑定。

I have a string property in my app's main window that is bound to a TextBox (I set the mode to "TwoWay").我在我的应用程序的主要 window 中有一个字符串属性绑定到一个文本框(我将模式设置为“TwoWay”)。

The only time that the value of the TextBox will update is when the window initializes. TextBox 的值唯一会更新的时间是 window 初始化时。

When I type into the TextBox, the underlying string properties value does not change.当我在 TextBox 中键入内容时,底层字符串属性值不会更改。

When the string property's value is changed by an external source (an event on Click, for example, that just resets the TextBox's value), the change doesn't propagate up to the TextBox.当字符串属性的值被外部源更改时(例如,Click 上的事件只是重置 TextBox 的值),更改不会向上传播到 TextBox。

What are the steps that I must implement to get two-way binding to work properly in even this almost trivial example?即使在这个几乎微不足道的示例中,我必须执行哪些步骤才能使双向绑定正常工作?

Most probably you're trying to bind to a .net CLR property instead of a WPF dependencyProperty (which provides Change Notification in addition to some other things). 很可能你正在尝试绑定到.net CLR属性而不是WPF dependencyProperty(除了其他一些东西之外还提供Change Notification)。
For normal CLR property, you'd need to implement INotifyPropertyChanged and force update on the textbox in the event handler for PropertyChanged. 对于普通的CLR属性,您需要在PropertyChanged的事件处理程序中实现INotifyPropertyChanged并强制更新文本框。

  • So make your object with the property implement this interface, raise the event in the property setter. 因此,使用属性实现此对象的对象,在属性设置器中引发事件。 (So now we have property change notification) (现在我们有财产变更通知)
  • Make sure the object is set as the DataContext property of the UI element/control 确保将对象设置为UI元素/控件的DataContext属性

This threw me off too when I started learning about WPF data binding. 当我开始学习WPF数据绑定时,这也让我失望了。

Update: Well OP, it would have been a waste of time if i was barking up the wrong tree.. anyways now since you had to dig a bit.. you'll remember it for a long time. 更新: OP,如果我在错误的树上咆哮,那将是浪费时间..反正现在,因为你不得不挖一点......你会记住它很长一段时间。 Here's the code snippet to round off this answer. 这是完成此答案的代码片段。 Also found that updating the textbox happens automatically as soon as I tab-out.. You only need to manually subscribe to the event and update the UI if your datacontext object is not the one implementing INotifyPropertyChanged. 还发现,只要我跳出选项,就会自动更新文本框。如果您的datacontext对象不是实现INotifyPropertyChanged的对象,则只需手动订阅该事件并更新UI。

MyWindow.xaml MyWindow.xaml

<Window x:Class="DataBinding.MyWindow" ...
    Title="MyWindow" Height="300" Width="300">
    <StackPanel x:Name="TopLevelContainer">
        <TextBox x:Name="txtValue"  Background="AliceBlue" Text="{Binding Path=MyDotNetProperty}" />
        <TextBlock TextWrapping="Wrap">We're twin blue boxes bound to the same property.</TextBlock>
        <TextBox x:Name="txtValue2"  Background="AliceBlue" Text="{Binding Path=MyDotNetProperty}" />
    </StackPanel>
</Window>

MyWindow.xaml.cs MyWindow.xaml.cs

public partial class MyWindow : Window, INotifyPropertyChanged
{
    public MyWindow()
    {
        InitializeComponent();
        this.MyDotNetProperty = "Go ahead. Change my value.";
        TopLevelContainer.DataContext = this;
    }

    private string m_sValue;
    public string MyDotNetProperty
    {
        get { return m_sValue; }
        set
        {
            m_sValue = value;
            if (null != this.PropertyChanged)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("MyDotNetProperty"));
            }
        }
    }

    #region INotifyPropertyChanged Members
    public event PropertyChangedEventHandler PropertyChanged;
    #endregion
}

I feel the need to add some precision: 我觉得需要增加一些精度:

"Two ways" data binding is more than "One way" data binding. “两种方式”数据绑定不仅仅是“单向”数据绑定。

"One way" data binding is a binding from a source to a depency property . “单向”数据绑定是从源到依赖属性的绑定。 The source must implement INotifyProertyChanged, in order to get change propagation from source to target. 源必须实现INotifyProertyChanged,以便从源到目标获得更改传播。

To get the " 2 way" , so to get a propagation from Target to Source, it depends on the binding mode which you set on the Binding . 要获得“2路”,那么要从Target传播到Source,它取决于您在Binding上设置的绑定模式。 If you don't set any BindingMode for your binding, the default Binding mode will be used, and this default mode is a characteristics fo your target Dependency Property. 如果没有为绑定设置任何BindingMode,则将使用默认的绑定模式,并且此默认模式是目标依赖项属性的特征。

Example: 例:

A Textbox bound to a string property, called "MyTextProperty". 绑定到字符串属性的文本框,名为“MyTextProperty”。 In the code , you bind Textbox.Text DependencyProperty to "MyTextProperty" on object "MyObject" 在代码中,将Textbox.Text DependencyProperty绑定到对象“MyObject”上的“MyTextProperty”

--> "one way" binding : the setter of "My TextProperty" must raise an event Property Changed,and "MyObject" must implement INotifyPropertyChanged. - >“单向”绑定:“My TextProperty”的setter必须引发一个Property Changed事件,而“MyObject”必须实现INotifyPropertyChanged。

--> "2 ways data binding": in addition to what is needed for "One way", bindingMode must be set to "2 ways". - >“2种方式数据绑定”:除了“单向”所需的内容之外,bindingMode必须设置为“2种方式”。 In this special case, the Text DependencyProperty for Textbox does have "2 ways" as default mode, so there is nothing else to do ! 在这种特殊情况下,Textbox的Text DependencyProperty确实有“2路”作为默认模式,所以没有别的事可做!

We might need to see the code. 我们可能需要查看代码。 Does your string property raise a PropertyChanged event? 您的字符串属性是否引发了PropertyChanged事件? Or (even better) is it implemented as a DependencyProperty? 或者(甚至更好)它是作为DependencyProperty实现的? If not, the bound TextBox won't know when the value changes. 如果不是,绑定的TextBox将不知道值何时更改。

As for typing into the TextBox and not seeing the property's value change, that may be because your TextBox isn't losing focus. 至于键入TextBox并且没有看到属性的值更改,这可能是因为您的TextBox没有失去焦点。 By default, bound TextBoxes don't write their values back to the source property until focus leaves the control. 默认情况下,绑定的TextBox不会将其值写回源属性,直到焦点离开控件。 Try tabbing out of it and seeing if the property value changes. 尝试跳出它并查看属性值是否发生变化。

Make sure that the binding specifies two way and when the property has a change, it is immediately transmitted to the holding property.确保绑定指定两种方式,并且当属性发生变化时,它会立即传输到持有属性。

 <TextBox Text="{Binding TextBuffer, 
                         UpdateSourceTrigger=PropertyChanged, 
                         Mode=TwoWay}"/>

The above assures that the TextBox input control Text property binds to, then sends the changes back to the string property named TextBuffer in an immediate, PropertyChanged , and TwoWay fashion.上面确保TextBox输入控件的Text属性绑定到,然后以立即、 PropertyChangedTwoWay方式将更改发送回名为TextBuffer的字符串属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM