【问题标题】:Can't bind to overridden WPF TextBox in ReactiveUI无法绑定到 ReactiveUI 中重写的 WPF 文本框
【发布时间】:2015-11-20 01:14:19
【问题描述】:

我有一个自定义的 TextBox,它会进行一些花哨的输入处理,以确保只输入数值:

public class NumericTextBox : TextBox
{
    // Some fancy input-handling here
}

我还有一个 ViewModel,它有一个公共属性来存储计数:

public class TheViewModel : ReactiveObject
{
    public int Count { get; set; }
}

我有一个视图,其中包含一个名为 Count 的 NumericTextBox:

<Window x:Class="MyProject.TheView"
    xmlns:controls="clr-namespace:MyProject.Controls">
    <controls:NumericTextBox
        Name="Count">
</Window>

将其绑定到 ViewModel:

public partial class TheView: Window, IViewFor<TheViewModel>
{
    public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register("ViewModel",
        typeof(TheViewModel),
        typeof(TheView));

    public TheView()
    {
        InitializeComponent();
    }

    /// <summary/>
    object IViewFor.ViewModel
    {
        get { return ViewModel; }
        set { ViewModel = (TheViewModel)value; }
    }

    /// <summary>
    /// The ViewModel corresponding to this specific View. This should be
    ///             a DependencyProperty if you're using XAML.
    /// </summary>
    public TheViewModel ViewModel
    {
        get
        {
            return (TheViewModel) GetValue(ViewModelProperty);
        }
        set
        {
            SetValue(ViewModelProperty, value);
            BindToViewModel();
        }
    }

    private void BindToViewModel()
    {
        this.Bind(ViewModel, vm => vm.Count, v => v.Count.Text);
    }
}

当我尝试编译时,VS 抱怨绑定到 TheView 中的 Count:

无法将 lambda 表达式转换为类型“对象”,因为它不是委托类型

如果我将 NumericTextBox 换成普通的 TextBox,它就可以正常工作。我有什么遗漏吗?

【问题讨论】:

    标签: c# wpf xaml mvvm reactiveui


    【解决方案1】:

    您应该使用 x:Name 而不是 Name。

    这里有一个关于x:Name and Name的详细解释

    就像您的自定义控件没有继承 Name 属性.. 有点..

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 2011-03-29
      • 2010-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-14
      • 2011-07-17
      相关资源
      最近更新 更多