【问题标题】:ReactiveUI binding with dependencyproperty and pass to viewmodelReactiveUI 与 dependencyproperty 绑定并传递给 viewmodel
【发布时间】:2020-01-23 13:28:27
【问题描述】:

我第一次开始使用 ReactiveUI(带有 WPF)并且遇到了一些我无法通过谷歌搜索或在文档上找到的问题。如何从 Control 的 DependencyProperty 中绑定属性?

我正在创建一个用户控件

public partial class MotorControlView: ReactiveUserControl<MotorControlViewModel>

在类里面我有依赖属性 MotorAxis

public static readonly DependencyProperty MotorAxisProperty = DependencyProperty.Register(
    "MotorAxis", typeof(MotorAxis), typeof(MotorControlView));

public MotorAxis MotorAxis
{
    get => (MotorAxis) GetValue(MotorAxisProperty);
    set => SetValue(MotorAxisProperty, value);
}

在视图内部有 TextBlock,它应该显示 MotorAxis(它是一个枚举)字符串值(NoVal/X/Y/Z)。 属性设置在MainWindow.XAML&lt;uc:MotorControlView MotorAxis="Y" /&gt;

问题是:

  • 如何使用 ReactiveUI 将标签的文本绑定到 MotorAxis 控件的属性?
  • 如何将值传递给 ViewModel

在构造函数中,它的值始终是默认值(NoVal),所以我认为我不能将它传递给 viewmodel 构造函数...

ViewModel 将根据这个参数负责访问 X/Y/Z 电机


我发现的唯一解决方案是这样做:

//In View:
public MotorControlView()
{
    InitializeComponent();
    ViewModel = new MotorControlViewModel();
    this.WhenActivated(dr =>
    {
        ViewModel.MotorAxis = this.MotorAxis;
    });
    this.Bind(ViewModel, vm => vm.MotorAxis, v => v.MotorAxisBlock.Text);
}

//在虚拟机中: 财产与 this.RaiseAndSetIfChanged(ref this.motorAxis, value)

有没有更优雅的方法来做到这一点,而无需在WhenActivated 中手动设置值?所以我可以在例如访问这个值。 VM的构造函数?

【问题讨论】:

    标签: reactiveui


    【解决方案1】:

    Reactiveui 使用绑定背后的代码。

    通常你会将它们放在构造函数中。

    reactiveui 方式的主要优点是类型安全。

    public MotorControlView
    {
      this.Bind(this.ViewModel, viewModel => viewModel.Axis, view => view.MotorControl.Text, axis => axis.ToString(), axisString => (MotorAxis)Enum.Parse(typeof(MotorAxis), axisString);
    }
    

    以上是在构造函数中做Bind。传递以下参数:

    1. 视图模型
    2. 指向视图模型上属性的表达式
    3. 指向视图上属性的表达式
    4. 一种转换器方法,获取视图模型上的属性,转换为字符串并将其放在视图上
    5. 一种转换器方法,将视图上的字符串转换为视图模型上的枚举。

    请参阅https://reactiveui.net/docs/handbook/data-binding/ 了解更多信息。

    【讨论】:

    • 是的,但是这个dependencyProperty怎么样?有没有办法在不手动 this.WhenActivated(d =&gt; { ViewModel.MotorAxis = this.MotorAxis; }); 的情况下初始化 VM 的 MotorAxis 属性?
    • 您可以在上面的第三个参数中将 ViewModel 绑定更改为view =&gt; view.MotorAxis。然后,您可以将另一个 Bind/OneWayBind 绑定到您的 View 对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 2012-08-25
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多