这是出于好奇的问题。我知道你不应该用这种方式构建任何真正的WPF应用程序。
在MainWindow Class中使用和使用如何将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));
}
}
}
所以我想在文本块中显示字符串。我认为这是一个简单的绑定,但我无法找到正确的语法。感谢
答案 0 :(得分:1)
您必须将窗口数据上下文设置为自身。
<Window.DataContext>
<Binding RelativeSource="{RelativeSource Self}"/>
</Window.DataContext>
然后你无法绑定到你的财产MyString
<TextBlock DockPanel.Dock ="Top" Height="50" Width="50"
Background ="AliceBlue" FontSize ="16" />
答案 1 :(得分:1)
在这种情况下,您只需执行以下操作:
<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>