【问题标题】:WPF TextBlock Binding doesn't workWPF TextBlock 绑定不起作用
【发布时间】:2014-08-25 15:52:09
【问题描述】:

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

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));
    }
}

【问题讨论】:

  • 你在哪里设置数据上下文?
  • @Sajeetharan 我认为 htis 正在设置 d:DataContext="{d:DesignData MainWindow}

标签: c# wpf xaml binding textblock


【解决方案1】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    • 2011-10-02
    • 1970-01-01
    • 2014-10-10
    相关资源
    最近更新 更多