如何阻止WPF绑定忽略它引起的PropertyChanged事件? [英] How to stop a WPF binding from ignoring the PropertyChanged event that it caused?

查看:516
本文介绍了如何阻止WPF绑定忽略它引起的PropertyChanged事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个TextBox绑定到ViewModel的Text属性,具有以下设置:

I have a TextBox bound to a ViewModel's Text property with the following setup:

Xaml

<TextBox Text="{Binding Text}"/>

C#

public class ViewModel : INotifyPropertyChanged
{
    public string Text
    {
        get
        {
            return m_Text;
        }
        set
        {
            if (String.Equals(m_Text, value))
            {
                return;
            }

            m_Text = value.ToLower();
            RaisePropertyChanged("Text");
        }
    }

    // Snip
}

当我在TextBox中输入一些东西时,它会成功地在ViewModel上设置Text属性。问题是WPF忽略由自己的更新引发的属性更改的事件。这导致用户没有看到他们键入的文本转换为小写。

When I type some stuff in to the TextBox it successfully sets the Text property on the ViewModel. The problem is that WPF ignores the property changed event that is raised by it's own update. This results in the user not seeing the text they typed converted to lowercase.

如何更改此行为,以便TextBox更新为小写字母? strong>

How can I change this behaviour so that the TextBox updates with lowercase text?

注意:这只是我用来说明WPF忽略事件的问题的一个例子。我不太感兴趣将字符串转换为小写或任何与String.Equals(string,string)有关的问题。

推荐答案

您可以通过使用Dispatcher.BeginInvoke在单独的调度程序调用中提高事件来实现此目的。

You can achieve this by raising the event in a seperate dispatcher call using Dispatcher.BeginInvoke

定义代理:

private delegate void RaisePropertyChangedDelegate(string property);

然后使用以下内容来提高事件

Then use the following to raise the event

Dispatcher.CurrentDispatcher.BeginInvoke(
    DispatcherPriority.Normal,
    new RaisePropertyChangedDelegate(RaisePropertyChanged), 
    "Text");

这篇关于如何阻止WPF绑定忽略它引起的PropertyChanged事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆