gpt4 book ai didi

mvvm - 如何在 MVVM ViewModel 中获取 Rx Observable 事件流

转载 作者:行者123 更新时间:2023-12-02 07:51:45 24 4
gpt4 key购买 nike

我刚刚在阅读 Rx HOL NET。找到后(示例使用 Windows 窗体):

var moves = Observable.FromEvent<MouseEventArgs>(frm, "MouseMove");

我想知道如何在某些 WPF MVVM 设置中实例化并传递对移动到 ViewModel 的引用?在我看来,尝试在 ViewModel 中过滤此数据流确实有意义。

或者,如何对 TextBox 中的键盘输入做类似的事情?例如,在这种情况下,您不会将某些文本屏蔽行为附加到 XAML 中的控件,而是让 VM 中的 Observer 过滤和验证键盘输入。

我完全偏离轨道了吗?

最佳答案

这是一个示例,说明您可以如何以 MVVM 方式实现网络服务字典。它包括三个部分:

  1. ObservablePropertyBacking 类,支持(T 的)属性,也实现了 IObservable
  2. MyViewModel 类。它包含一个 CurrentText 属性,该属性使用 ObservablePropertyBacking 作为后备存储。它还会观察此属性的值并使用它来调用字典网络服务。
  3. 包含文本框的 MainView.xaml。它的 Text 属性双向绑定(bind)到 View 模型上的 CurrentText 属性。

MyViewModel.cs:

class MyViewModel: INotifyPropertyChanged
{
#region INotifyPropertyChanged implementation

public event PropertyChangedEventHandler PropertyChanged;

private void RaisePropertyChanged(string p)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(p));
}

#endregion

public MyViewModel()
{
SetupProperties();
}

#region CurrentText

/* We use a special class for backing of the CurrentText property. This object
* holds the value of the property and also dispatches each change in an observable
* sequence, i.e. it implements IObservable<T>.
*/
private ObservablePropertyBacking<string> _textInput;
public string CurrentText
{
get { return _textInput.Value; }
set
{
if (value == _textInput.Value) { return; }
_textInput.Value = value;
RaisePropertyChanged("CurrentText");
}
}

#endregion

/* Create property backing storage and subscribe UpdateDictionary to the observable
* sequence. Since UpdateDictionary calls a web service, we throttle the sequence.
*/
private void SetupProperties()
{
_textInput = new ObservablePropertyBacking<string>();
_textInput.Throttle(TimeSpan.FromSeconds(1)).Subscribe(UpdateDictionary);
}

private void UpdateDictionary(string text)
{
Debug.WriteLine(text);
}
}

ObservablePropertyBacking.cs:

public class ObservablePropertyBacking<T> : IObservable<T>
{
private Subject<T> _innerObservable = new Subject<T>();

private T _value;
public T Value
{
get { return _value; }
set
{
_value = value;
_innerObservable.OnNext(value);
}
}

public IDisposable Subscribe(IObserver<T> observer)
{
return _innerObservable
.DistinctUntilChanged()
.AsObservable()
.Subscribe(observer);
}
}

主页.xaml:

  <Window 
x:Class="RxMvvm_3435956.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox
Text="{Binding CurrentText, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</Window>

关于mvvm - 如何在 MVVM ViewModel 中获取 Rx Observable 事件流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3435956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com