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

时间:2011-11-29 05:37:54

标签: c# wpf mvvm

我有文本框,我将其Text属性绑定到Window的ModalView中的MainTxtBoxTxt属性。当MainTxtBoxTxt更改它影响到TextBox时,但当TextBox的Text属性发生更改时,它不会影响ModelView中的MainTxtBoxTxt。问题是什么?< / p>

<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);
        }
    }

3 个答案:

答案 0 :(得分:2)

试试这个

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

答案 1 :(得分:1)

使用以下内容:

<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将在文本框中的文本每次更改时更新视图模型。

答案 2 :(得分:1)

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

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

LostFocus - 当焦点远离当前控件时,更改会反映出来。

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

明确 - 顾名思义,它出现在您的命令中。您必须调用UpdateSource方法,否则更改将不会传播回源