gpt4 book ai didi

wpf - 如何在 xaml 中对公共(public)属性进行数据绑定(bind)

转载 作者:行者123 更新时间:2023-12-04 13:10:07 26 4
gpt4 key购买 nike

我要做的就是将公共(public)属性绑定(bind)到 textBlock。我在这里做错了什么?

namespace WpfApplication1
{

public partial class MainWindow : Window
{

public string test { get; set; }

public MainWindow()
{
test = "this is a test";
InitializeComponent();
}
}
}

<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">
<Window.Resources>
<ObjectDataProvider x:Key="test"></ObjectDataProvider>
</Window.Resources>
<Grid>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="108,58,0,0" Name="textBlock1" VerticalAlignment="Top" Text="{Binding Source={StaticResource test}}" />
</Grid>

最佳答案

您可以简单地添加数据上下文并访问您的属性

public partial class MainWindow : Window,INotifyPropertyChanged
{
private string _test;
public string test
{
get
{
return _test;
}
set
{
_test = value;
OnPropertyChanged("test");
}
}
public MainWindow()
{
test = "this is a test";
InitializeComponent();
DataContext = this;
}

public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(String name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
<TextBlock Height="23" HorizontalAlignment="Left" Margin="108,58,0,0" Name="textBlock1" VerticalAlignment="Top" Text="{Binding test}"/>

另请查看此帖子以了解何时使用 ObjectDataProvider 的详细信息

http://bea.stollnitz.com/blog/?p=22

关于wpf - 如何在 xaml 中对公共(public)属性进行数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4740217/

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