将 UWP 控件绑定到代码隐藏 属性
Binding UWP control to code behind property
我正在开发 UWP 应用程序,我创建了新的用户控件,我想将它绑定到控件后面的代码中的依赖项 属性(没有数据上下文)。
隐藏代码:
public Brush Fill
{
get { return (Brush)GetValue(FillProperty); }
set { SetValue(FillProperty, value); }
}
// Using a DependencyProperty as the backing store for Fill. This enables animation, styling, binding, etc...
public static readonly DependencyProperty FillProperty =
DependencyProperty.Register("Fill", typeof(Brush), typeof(MyControl), new PropertyMetadata(new SolidColorBrush(Colors.Black)));
XAML:
...
<Grid>
<Path Fill="{Binding ????}" Stretch="Fill">
...
</Path>
</Grid>
我希望我的路径填充 属性 将绑定到代码后面的 属性 Fill
(数据上下文应该包含不同的数据,所以我不能在这里使用它)
我如何在 UWP 中执行此操作?
您应该能够使用绑定的 ElementName 属性 来规避数据上下文,就像普通 WPF 允许您做的那样。
如果 属性 是用户控件的一部分,您需要通过 x:Name 为 xaml 中的用户控件分配一个名称才能访问它
<UserControl [...] x:Name="Control"...`
然后使用 {Binding ElementName=Control, Path=Fill}
之类的东西,只要 Fill 是您的用户控件的 属性。
x:Bind
可以完美地解决这个问题。注意 x:Bind
将查找在您的 XAML 的代码隐藏中定义的属性、方法和事件。这是一个比 ElementName
.
更高效的绑定
<Path Fill="{x:Bind Fill, Mode=OneWay}" />
我正在开发 UWP 应用程序,我创建了新的用户控件,我想将它绑定到控件后面的代码中的依赖项 属性(没有数据上下文)。
隐藏代码:
public Brush Fill
{
get { return (Brush)GetValue(FillProperty); }
set { SetValue(FillProperty, value); }
}
// Using a DependencyProperty as the backing store for Fill. This enables animation, styling, binding, etc...
public static readonly DependencyProperty FillProperty =
DependencyProperty.Register("Fill", typeof(Brush), typeof(MyControl), new PropertyMetadata(new SolidColorBrush(Colors.Black)));
XAML:
...
<Grid>
<Path Fill="{Binding ????}" Stretch="Fill">
...
</Path>
</Grid>
我希望我的路径填充 属性 将绑定到代码后面的 属性 Fill
(数据上下文应该包含不同的数据,所以我不能在这里使用它)
我如何在 UWP 中执行此操作?
您应该能够使用绑定的 ElementName 属性 来规避数据上下文,就像普通 WPF 允许您做的那样。
如果 属性 是用户控件的一部分,您需要通过 x:Name 为 xaml 中的用户控件分配一个名称才能访问它
<UserControl [...] x:Name="Control"...`
然后使用 {Binding ElementName=Control, Path=Fill}
之类的东西,只要 Fill 是您的用户控件的 属性。
x:Bind
可以完美地解决这个问题。注意 x:Bind
将查找在您的 XAML 的代码隐藏中定义的属性、方法和事件。这是一个比 ElementName
.
<Path Fill="{x:Bind Fill, Mode=OneWay}" />