.net c#在 ReactiveUI 中订阅用户控件上的依赖项属性

Subscribing to a dependency property on a user control in ReactiveUI
2021-12-04
  •  译文(汉语)
  •  原文(英语)

我正在尝试使用 ReactiveUI 订阅 UserControl 上依赖项属性的更改.

我看到了另一个堆栈溢出答案(结合依赖属性)中描述的技术,但我在某处的实现出错了.即使在下面的简单情况下,我也无法在依赖属性更改时触发订阅.

这是我的代码的相关部分:

public partial class AutoCompleteBox : UserControl
{
    public static readonly DependencyProperty SelectedItemProperty =
    DependencyProperty.Register("SelectedItem",typeof(object),typeof(AutoCompleteBox),
    new FrameworkPropertyMetadata{BindsTwoWayByDefault = true});

    public object SelectedItem
    {
        get { return (object)GetValue(SelectedItemProperty); }
        set { SetValue(SelectedItemProperty, value); }
    }

    public AutoCompleteBox()
    {
        InitializeComponent();               
        this.WhenAny(m=>m.SelectedItem,m=>m.Value)
            .Subscribe(_=>
            Console.WriteLine("Selected Item Changed!"));
    }
}

编辑

我正在使用 ReactiveUI 版本 4.4.2.0

在进一步调查中,当我在主项目中使用用户控件时,订阅调用似乎确实有效,只是在我用于测试它的小项目中无效.我不确定有什么区别.

解决过程1

几个问题:

  1. 您的代码中是否有对 ReactiveUI.Xaml 的引用?如果这不能正确加载,这将不起作用
  2. 你使用的是什么版本的 ReactiveUI?

I'm trying to use ReactiveUI to subscribe to changes in a dependency property on a UserControl.

I saw the technique described in another stack overflow answer(Combine dependency properties) but I'm going wrong with the implementation somewhere. Even in the simple case below, I can't get the subscription to fire when the dependency property changes.

Here's the relevant parts of my code:

public partial class AutoCompleteBox : UserControl
{
    public static readonly DependencyProperty SelectedItemProperty =
    DependencyProperty.Register("SelectedItem",typeof(object),typeof(AutoCompleteBox),
    new FrameworkPropertyMetadata{BindsTwoWayByDefault = true});

    public object SelectedItem
    {
        get { return (object)GetValue(SelectedItemProperty); }
        set { SetValue(SelectedItemProperty, value); }
    }

    public AutoCompleteBox()
    {
        InitializeComponent();               
        this.WhenAny(m=>m.SelectedItem,m=>m.Value)
            .Subscribe(_=>
            Console.WriteLine("Selected Item Changed!"));
    }
}

Edit

I'm using ReactiveUI version 4.4.2.0

On further investigation, the subscribe call does appear to work when I use the user control in my main project, just not in the small project that I'm using for testing it. I'm not sure what the difference could be.

Solutions1

A few questions:

  1. Do you have a reference to ReactiveUI.Xaml in your code? If that doesn't load properly, this won't work
  2. What version of ReactiveUI are you using?
转载于:https://stackoverflow.com/questions/15208591/subscribing-to-a-dependency-property-on-a-user-control-in-reactiveui

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入