寻找一种在MVVM应用程序中更新非依赖项属性的方法

时间:2015-01-15 15:10:10

标签: c# wpf mvvm

我正在WPF中编写terimnal应用程序。我从嵌入式设备接收字符,然后更新与ViewModel绑定的TextBox.Text属性。

问题是当我更新text属性时TextBox Caret被重置。我想要做的是在我的viewModel中保存一个Caret参数并将其绑定到TextBox的Caret属性,但TextBox Caret不是依赖属性,我不想直接从我的视图模型访问该视图。

您是否熟悉不破坏MVVM模式的正确解决方案?

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以添加附加属性以绑定非依赖项属性。下面的例子我已经为文本框的CaretIndex属性创建了它。

<Window x:Class="Converter_Learning.Window7"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local="clr-namespace:Converter_Learning"
    Title="Window7" Height="500" Width="500">
<Grid FocusManager.FocusedElement="{Binding ElementName=txt}">
    <TextBox x:Name="txt" Text="Hiiiiiiiiiiiiiii" local:TextBoxHelper.Caret="{Binding Caret}" />
</Grid>

public partial class Window7 : Window
{
    public Window7()
    {
        InitializeComponent();            
        this.DataContext= new CaretViewModel();
    }
}

public class CaretViewModel : INotifyPropertyChanged
{
    private int myVar;

    public int Caret
    {
        get { return myVar; }
        set { myVar = value; Notify("Caret"); }
    }

    public CaretViewModel()
    {
        Caret = 5;
    }
    public event PropertyChangedEventHandler PropertyChanged;

    void Notify(string property)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}

public static class TextBoxHelper
{

    public static int GetCaret(DependencyObject obj)
    {
        return (int)obj.GetValue(CaretProperty);
    }

    public static void SetCaret(DependencyObject obj, int value)
    {
        obj.SetValue(CaretProperty, value);
    }

    public static readonly DependencyProperty CaretProperty =
        DependencyProperty.RegisterAttached(
            "Caret",
            typeof(int),
            typeof(TextBoxHelper),
            new FrameworkPropertyMetadata(0, CaretChanged));

    private static void CaretChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        TextBox tb = obj as TextBox;
        if (tb != null)
        {
            int newValue = (int)e.NewValue;

            if (newValue != tb.CaretIndex)
            {                    
                tb.CaretIndex = (int)newValue;
            }
        }
    }

}