gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:58:21 25 4
gpt4 key购买 nike

我想在我的类中动态更改 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 不显示“Setting”。这里有什么问题?

最佳答案

如果您要绑定(bind) - 为什么不直接在 XAML 中进行呢?查看您的代码有点毫无意义 - 您不妨去

Footer_text.Text = "Setting";

理想情况下,您应该在 XAML 中执行此操作,或者至少为其提供绑定(bind)的内容

<TextBlock Text="{Binding SomeProperty}" />

我不确定为什么要将“字符串”本身绑定(bind)到任何东西...您有需要绑定(bind)到文本属性的对象吗?

同时使用

Binding("")

那有什么作用?空白路径?不确定绑定(bind)目标是什么......你试过了吗

Binding()

代替?

编辑:

另外,您的绑定(bind)未更新控件的原因可能是因为您尚未绑定(bind)到实现 INotifyPropertyChanged 或类似接口(interface)的对象。控件需要知道值何时发生变化,所以我想绑定(bind)到“字符串”不会在 TextBlock 发生变化时给予适当的通知

编辑 2:

这是绑定(bind)工作的一个简单示例:

我的窗口类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";
}
}

要绑定(bind)的对象(使用 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,但会更新文本框。

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

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