简单的WPF/XAML问题.在XAML中,如何在给定的上下文中引用Self/this对象?在具有主窗口,一个控件和窗口的编码C#属性的非常基本的应用程序中,我想将控件的属性绑定到窗口的手写编码属性.
在代码中,这很容易 - 在Window的构造函数中,我添加了这个:
Binding bind = new Binding();
bind.Source = this;
bind.Path = new PropertyPath("ButtonWidth");
button1.SetBinding(WidthProperty, bind);
Run Code Online (Sandbox Code Playgroud)
显然,我有一个名为ButtonWidth的属性,以及一个名为button1的控件.我无法弄清楚如何在XAML中执行此操作.以下示例的各种尝试都没有奏效:
<Button x:Name="button1" Width="{Binding Source=Self Path=ButtonWidth}"/>
<Button x:Name="button1" Width="{Binding RelativeSource={RelativeSource Self} Path=ButtonWidth}"/>
Run Code Online (Sandbox Code Playgroud)
等等
谢谢
Arc*_*rus 78
首先在绑定中使用RelativeSource和Path之间的逗号:
<Button x:Name="button1" Width="{Binding RelativeSource={RelativeSource Self},
Path=ButtonWidth}"/>
Run Code Online (Sandbox Code Playgroud)
其次,RelativeSource绑定到Button.Button没有名为ButtonWidth的属性.我猜你需要绑定到你的父控件.
所以试试这个RelativeSource绑定:
<Button x:Name="button1" Width="{Binding RelativeSource=
{RelativeSource FindAncestor, AncestorType={x:Type YourNamespace:YourParentControl}},
Path=ButtonWidth}"/>
Run Code Online (Sandbox Code Playgroud)
Cli*_*ent 31
我认为你在寻找的是:
<Window x:Class = "blah blah all the regular stuff"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
>
Run Code Online (Sandbox Code Playgroud)
Dam*_*ian 29
我必须处理RelativeSource之类的一种方法是命名根XAML元素:
<Window x:Class="TestApp2.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="_this"
>
<Grid>
<Button x:Name="button" Width="{Binding ElementName=_this,Path=ButtonWidth}" />
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
如果要设置DataContext,还可以执行以下操作:
<Window x:Class="TestApp2.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="_this"
>
<Grid DataContext="{Binding ElementName=_this}">
<Button x:Name="button" Width="{Binding Path=ButtonWidth}" />
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
我发现这是一个很好的技巧,不必记住RelativeSource绑定的所有复杂性.