如何在 xaml 中对公共属性进行数据绑定
我想做的就是将公共属性绑定到文本块。我在这里做错了什么?
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>
All I am trying to do is bind a public property to a textBlock. What am I doing wrong here?
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以简单地添加数据上下文并访问您的属性。
另请查看这篇文章,了解何时使用 ObjectDataProvider
的详细信息http://bea.stollnitz.com/blog/?p=22
You can simply add a datacontext and access your property
Also check this post for details of when to use an ObjectDataProvider
http://bea.stollnitz.com/blog/?p=22
首先,您需要类来实现 INotifyPropertyChanged 或属性为 DependencyProperty 用于更改文本框文本上的属性值更改,
您可以通过为该窗口指定名称并使用 ElementName 属性来绑定到该属性,如下所示。
At first you need you class to implement INotifyPropertyChanged or a property to be DependencyProperty for changing property value on textbox text change,
Than you can bind to that property by giving name to that window, and using ElementName property like this.
您实际上不需要实现 INotifyPropertyChanged。但是,这将是一次性数据绑定。
例如在 XAML 中:
在代码中:
You actually don't need to implement INotifyPropertyChanged. However, this will be a one time data binding.
For example in XAML:
In Code: