它不会改变属性,这是绑定(模式TwoWay)

它不会改变属性,这是绑定(模式TwoWay)

问题描述:

我有文本框,我把它的Text属性绑定到WindowModalView中的MainTxtBoxTxt属性。当MainTxtBoxTxt改变它影响到TextBox,但是当TextBox的Text属性改变它不影响到ModelView中的MainTxtBoxTxt.What是什么问题?它不会改变属性,这是绑定(模式TwoWay)

<cstmTxtBox:CustomTextBox Grid.Row="0" TextWrapping="Wrap" FontSize="16" x:Name="TxtBox" cstmTxtBox:CustomTextBox.CaretIndex="{Binding Path=CaretIndex, Mode=TwoWay}" Text="{Binding Path=MainTxtBoxText,Mode=TwoWay}" > 

CustomTxtBox

public class CustomTextBox : TextBox 
    { 

     public CustomTextBox() 
     { 

     } 
     public static DependencyProperty CaretIndexProperty =DependencyProperty.RegisterAttached("CaretIndex",typeof(int),typeof(CustomTextBox),new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsRender)); 
     public static void SetCaretIndex(UIElement element, int value) 
     { 
      element.SetValue(CaretIndexProperty, value); 
     } 
     public static int GetCaretIndex(UIElement element) 
     { 
      return (int)element.GetValue(CaretIndexProperty); 
     } 
    } 
+0

你应该发布一些如何在xaml和你的属性中绑定的代码 – MaRuf

+0

CustomTextBox的Text属性是一个DependencyProperty是)?从CustomTextBox发布相关代码。 – Nawaz

+0

我没有附加该属性。 –

试试这个

Text="{Binding Path=MainTxtBoxText,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
+0

谢谢,它帮助:) –

使用下列内容:

<cstmTxtBox:CustomTextBox Grid.Row="0" TextWrapping="Wrap" FontSize="16" x:Name="TxtBox" cstmTxtBox:CustomTextBox.CaretIndex="{Binding Path=CaretIndex, Mode=TwoWay}" Text="{Binding Path=MainTxtBoxText,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" > 

通过对焦点默认文本框更新视图模型 丢失。每次更改文本框中的文本时,指定UpdateSourceTrigger = PropertyChanged将更新视图模型。

您在代码中缺少UpdateSourceTrigger属性,该属性指定数据更改应如何反映在模型属性中。为了详细说明,UpdateSoruceTrigger酒店有四个选项可供选择: -

默认 - 返回目标依赖属性的默认UpdateSourceTrigger值。它随控制而变化。

LostFocus - 当焦点从当前控件移开时会发生变化。

PropertyChanged - 反映数据更改后发生的更改。对于文本框,只要按下某个键,就会发生更改。

明确 - 顾名思义,它发生在您的命令。你必须调用UpdateSource方法或者更改不会传播回来源