与单个Window类绑定
本文关键字:绑定 Window 单个 | 更新日期: 2023-09-27 18:26:15
这是不安全的问题。我知道你不应该用这种方式构建任何真正的WPF应用程序。
在MainWindow类中工作并仅使用它如何将XAML元素绑定到CLR属性?
这是我的XAML。
<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>
<TextBlock DockPanel.Dock ="Top" Height="50" Width="50"
Background ="AliceBlue" FontSize ="16" />
</Grid>
</Window>
并编码
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
string _myString = "hello world";
public string MyString
{
get { return _myString; }
}
public MainWindow()
{
InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(
this, new PropertyChangedEventArgs(propName));
}
}
}
所以我想在文本块中显示字符串。我认为这是一个简单的绑定,但我找不到正确的语法。感谢
您必须将窗口数据上下文设置为自身。
<Window.DataContext>
<Binding RelativeSource="{RelativeSource Self}"/>
</Window.DataContext>
则您无法绑定到您的财产MyString
<TextBlock DockPanel.Dock ="Top" Height="50" Width="50"
Background ="AliceBlue" FontSize ="16" />
在这种情况下,您可以简单地执行:
<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"
x:Name="MainWindow">
<Grid>
<TextBlock DockPanel.Dock ="Top" Height="50" Width="50"
Background ="AliceBlue" FontSize ="16"
Text="{Binding MyString, ElementName=MainWindow}" />
</Grid>
</Window>