Luc*_*cas 1 c# data-binding wpf textblock
我想动态更改TextBlock
班级中的文本。
XAML 代码:
<TextBlock Name="Footer_text" Text=""/>
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
我检查了最后一行,并且Footer_text.Text
设置正确。( Footer_text.Text="Setting"
),但TextBlock
在我的应用程序中没有显示“设置”。这里有什么问题?
如果您正在绑定 - 为什么不直接在 XAML 中进行呢?看看你的代码,这有点毫无意义——你不妨去
Footer_text.Text = "Setting";
Run Code Online (Sandbox Code Playgroud)
理想情况下,您应该在 XAML 中执行此操作,或者至少提供一些可以绑定到的内容
<TextBlock Text="{Binding SomeProperty}" />
Run Code Online (Sandbox Code Playgroud)
我不知道为什么你要把一个“字符串”绑定到任何东西上……你有一个需要绑定到 text 属性的对象吗?
还使用
Binding("")
Run Code Online (Sandbox Code Playgroud)
那有什么作用?空白路径?不确定那里的绑定目标是什么......你有没有试过
Binding()
Run Code Online (Sandbox Code Playgroud)
反而?
编辑:
此外,您的绑定未更新控件的原因可能是因为您尚未绑定到实现 INotifyPropertyChanged 或类似接口的对象。控件需要知道值何时发生更改,因此我认为绑定到“字符串”不会在 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>
Run Code Online (Sandbox Code Playgroud)
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";
}
}
Run Code Online (Sandbox Code Playgroud)
要绑定到的对象(使用 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));
}
}
Run Code Online (Sandbox Code Playgroud)
单击按钮会更改 SomeObject.Name,但会更新文本框。