gpt4 book ai didi

c# - 属性未在文本框中更新 - WPF

转载 作者:行者123 更新时间:2023-11-30 22:09:21 26 4
gpt4 key购买 nike

我在将属性 Message 绑定(bind)到 View 时遇到问题。回调从 WCF 服务返回结果。我正在尝试将此结果分配给属性 Message。我的文本框从未更新为新值 - 它始终显示测试。

public class CallbackHandler : IDataExchangeCallback, INotifyPropertyChanged 
{
public CallbackHandler()
{
this.Message = "TEST";
}

public void Result(string result)
{
Message = result;
}

private string _message;
public string Message
{
get { return _message; }
set
{
_message = value;
OnPropertyChanged("Message");
}
}

public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;

if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}

<Window x:Class="guiClient.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tb="http://www.hardcodet.net/taskbar"
xmlns:local="clr-namespace:guiClient"
Title="DataExchangeClient" Height="76" Width="297" WindowStyle="SingleBorderWindow" MinHeight="50" MinWidth="50" MaxWidth="300">
<Window.DataContext>
<local:CallbackHandler/>
</Window.DataContext>
<Grid>
<TextBox HorizontalAlignment="Left" Height="45" TextWrapping="Wrap" VerticalAlignment="Top" Width="289" Text="{Binding Path=Message}"/>
</Grid>
</Window>

这是界面:

------来自用户蜂鸣器

回调定义如下:

IDataExchangeCallback Callback
{
get
{
return OperationContext.Current.GetCallbackChannel<IDataExchangeCallback>();
}
}

和界面:

// The callback interface is used to send messages from service back to client.
// The Result operation will return the current result after each operation.
public interface IDataExchangeCallback
{
[OperationContract(IsOneWay = true)]
void Result(string result);
}

最佳答案

原因可能是您没有在 UI 线程上引发 PropertyChanged,因为您是从回调中调用它。尝试使用 Dispatcher 确保在 UI 线程上引发事件:

protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;

if (handler != null)
{
Application.Current.Dispatcher.Invoke(() =>
handler(this, new PropertyChangedEventArgs(propertyName)));
}
}

关于c# - 属性未在文本框中更新 - WPF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21646863/

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