【问题标题】:Get Dependency Property Value in UserControl Code Behind在后面的 UserControl 代码中获取依赖属性值
【发布时间】:2016-01-12 07:14:27
【问题描述】:

我是 WPF 新手。我正面临以下问题。我有一个用户控件,这是用户控件的代码

自定义控制代码

public partial class CustomCanvas : UserControl
{
    public CustomCanvas()
    {
        InitializeComponent();
        DrawCanvas();
    }

    private void DrawCanvas()
    {
        //TODO:
        //Get the Dictionary Value from Parent Bound Property
    }

    public Dictionary<string, List<Shapes>> ShapesData
    {
        get { return (Dictionary<string, List<Shapes>>)GetValue(ShapesDataProperty); }
        set { SetValue(ShapesDataProperty, value); }
    }

    public static readonly DependencyProperty ShapesDataProperty =
        DependencyProperty.Register("ShapesData", typeof(Dictionary<string, List<Shapes>>), typeof(CustomCanvas), new PropertyMetadata(ShapesDataChanged));

    private static void ShapesDataChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var value = e.NewValue;
    }
}

主窗口代码

<Grid>
    <uc:CustomCanvas ShapesData="{Binding ShData}" ></uc:CustomCanvas>
</Grid>

ShapesData 的值与以下代码绑定。

ShData = new Dictionary<string, List<Shapes>>()
        {
            {"Week 1", new List<Shapes>() {Shapes.Circle, Shapes.Rectangle}},
            {"Week 2", new List<Shapes>() {Shapes.Circle}},
            {"Week 3", new List<Shapes>() {Shapes.Rectangle}}
        };

现在我的问题是,在 CustomControl DrawCanvas 方法中,我想获取父级中的有界值。任何人都可以指导我。

P.S:我知道如何使用相对的 RelativeSource 和 Mode 作为 FindAncestor 在子级中绑定此值。在这里,我只想获取值并处理该字典数据。在 ShapesDataChanged 中,我可以轻松访问数据,但问题在于在 DrawCanvas 函数中获取数据。

提前致谢。

【问题讨论】:

  • 您应该简单地使用ShapesData 属性。它将返回绑定值。
  • @ghord 这就是我最初的想法。但不幸的是它不起作用,我不明白为什么它不起作用,因为它很合乎逻辑。
  • 得到了答案。 @ghord 你是对的。问题是我没有在依赖属性更改时调用 DrawCanvase。

标签: c# .net wpf data-binding wpf-controls


【解决方案1】:

您可以使用 DependencyObject 的 GetValue() 方法。

var theValueYouNeeded = CustomCanvas.GetValue(ShapesDataProperty);
Dictionary<string, List<Shapes>> value = (Dictionary<string, List<Shapes>>)theValueYouNeeded;
....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 2011-07-29
    • 2019-12-08
    • 2010-10-24
    相关资源
    最近更新 更多