TextBlock中的绑定在WPF中不起作用

时间:2012-06-30 13:23:35

标签: c# wpf data-binding textblock

我想动态更改班级中的TextBlock文字。

XAML的代码

<TextBlock Name="Footer_text"  Text=""/>

C#

string footerMainMenuText = "Setting";
Binding  set = new Binding("");
set.Mode = BindingMode.OneWay;
set.Source = footerMainMenuText;
Footer_text.DataContext = footerMainMenuText;
Footer_text.SetBinding(TextBlock.TextProperty, set);

我检查了最后一行,Footer_text.Text设置正确。 (Footer_text.Text="Setting"),但我的应用程序中的TextBlock并未显示“设置”。这里有什么问题?

1 个答案:

答案 0 :(得分:4)

如果你有约束力 - 为什么不在XAML中呢?看看你的代码,这是毫无意义的 - 你可能只是去

Footer_text.Text = "Setting";

理想情况下,您应该在XAML中执行此操作,或者至少为其提供绑定到

的内容
<TextBlock Text="{Binding SomeProperty}" />

我不确定为什么你会把它自己的'string'绑定到任何东西......你有一个你需要绑定到text属性的对象吗?

也使用

Binding("")

那是做什么的?一条空白路径?不知道绑定目标会在那里......你试过吗

Binding()

代替?

编辑:

此外,绑定未更新控件的原因可能是因为您尚未绑定到实现INotifyPropertyChanged或类似接口的对象。控件需要知道值何时发生了变化,所以我认为绑定到'string'并不会在TextBlock发生变化时给出正确的通知

编辑2:

以下是绑定工作的快速示例:

我的窗口类Window.cs:

<Window x:Class="WpfApplication1.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>
        <StackPanel>
        <TextBlock x:Name="txtName" Text="{Binding Name}"></TextBlock>
            <Button Click="Button_Click">Click me 1</Button>
            <Button Click="Button_Click_1">Click me 2</Button>
        </StackPanel>
    </Grid>
</Window>

Window.xaml.cs中的代码

public partial class MainWindow : Window
{
    SomeObjectClass obj = new SomeObjectClass();
    public MainWindow()
    {
        InitializeComponent();

        txtName.DataContext = obj;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        obj.Name = "Hello World";
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        obj.Name = "Goobye World";
    }
}

要绑定的对象(使用INotifyPropertyChanged)

class SomeObjectClass : INotifyPropertyChanged
{
    private string _name = "hello";
    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
            OnPropertyChanged("Name");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string PropertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
    }
}

单击按钮更改SomeObject.Name,但它会更新文本框。

相关问题