【问题标题】:Binding UWP control to code behind property将 UWP 控件绑定到代码隐藏属性
【发布时间】:2017-07-31 09:16:20
【问题描述】:

我正在开发 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 中做到这一点?

【问题讨论】:

    标签: c# uwp uwp-xaml


    【解决方案1】:

    x:Bind 可以完美解决这个问题。注意x:Bind 将寻找在您的 XAML 代码隐藏中定义的属性、方法和事件。这是一个比ElementName 更高效的绑定。

    <Path Fill="{x:Bind Fill, Mode=OneWay}" />
    

    【讨论】:

      【解决方案2】:

      您应该能够使用绑定的 ElementName 属性来绕过数据上下文,就像普通 WPF 允许您做的那样。

      如果属性是用户控件的一部分,您需要通过 x:Name 为 xaml 中的用户控件分配一个名称才能访问它

      <UserControl [...] x:Name="Control"...`
      

      然后使用{Binding ElementName=Control, Path=Fill} 之类的东西,只要 Fill 是您的用户控件的属性。

      【讨论】:

        猜你喜欢
        • 2012-02-04
        • 2016-09-05
        • 1970-01-01
        • 2015-03-25
        • 2019-01-03
        • 1970-01-01
        • 1970-01-01
        • 2010-12-16
        • 2019-06-07
        相关资源
        最近更新 更多