【问题标题】:Looking for a way to update a non-dependency property in MVVM application寻找一种方法来更新 MVVM 应用程序中的非依赖属性
【发布时间】:2015-01-15 15:10:10
【问题描述】:

我正在 WPF 中编写终端应用程序。我从嵌入式设备接收字符并更新绑定到我的 ViewModel 的 TextBox.Text 属性。

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

您是否熟悉不会破坏 MVVM 模式的适当解决方案?

提前致谢。

【问题讨论】:

  • 您可以尝试从System.Windows.Interactivity 创建一个自定义Behavior。

标签: c# wpf mvvm


【解决方案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;
            }
        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    相关资源
    最近更新 更多