gpt4 book ai didi

c# - WPF TextBlock 绑定(bind)不起作用

转载 作者:太空狗 更新时间:2023-10-29 17:41:54 27 4
gpt4 key购买 nike

我尝试将 TextBlockText 属性绑定(bind)到我的属性,但文本没有更新。

XAML

<Window x:Name="window" x:Class="Press.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
Title="Press analyzer" Height="350" Width="525" ContentRendered="Window_ContentRendered"
d:DataContext="{d:DesignData MainWindow}">
...
<StatusBar Name="StatusBar" Grid.Row="2" >
<TextBlock Name="StatusBarLabel" Text="{Binding Message}"/>
</StatusBar>
</Window>

C#

public partial class MainWindow : Window, INotifyPropertyChanged 
{
private string _message;
public string Message
{
private set
{
_message = value;
OnPropertyChanged("Message");
}
get
{
return _message;
}
}
public event PropertyChangedEventHandler PropertyChanged;

[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}

最佳答案

在 MainWindow 的构造函数中将 MainWindow 的 DataContext 设置为自身以解析绑定(bind):

public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}

如果您不设置 DataContext,则必须使用 RelativeSource 从 XAML 显式解析绑定(bind):

<TextBlock Name="StatusBarLabel"
Text="{Binding Message, RelativeSource={RelativeSource
Mode=FindAncestor, AncestorType=Window}}"/>

注意 - 您可以随时去检查 Visual Studio 的输出窗口是否有任何绑定(bind)错误。

关于c# - WPF TextBlock 绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24572063/

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