简体   繁体   English

窗口和用户控件中的WPF绑定

[英]WPF bindings in window and user control

I have Control Library and WPF application. 我有控件库和WPF应用程序。 I need to create my custom control to vizualize graph. 我需要创建我的自定义控件以使图形更生动。 So I made GraphControl and set there custom attribute GraphData: 因此,我进行了GraphControl并在其中设置了自定义属性GraphData:

public static readonly DependencyProperty GraphDataProperty = DependencyProperty.Register("GraphData", typeof(Graph), typeof(GraphControl));

public Graph GraphData
{
    get { return (Graph)GetValue(GraphDataProperty); }
    set
    {
        SetValue(GraphDataProperty, value);
        TextBlock.Text = "asdfasdfasdfasdfasd";
    }
}

This part is done, but now I want to bind GraphData to property in MainWindow of application where GraphControl is nested. 这部分完成了,但是现在我想将GraphData绑定到嵌套GraphControl的应用程序的MainWindow中的属性。 I mean I want to change some graphData property in MainWindow and when I do that, graph rerenders, and all rendering occurs inside control, not window. 我的意思是我想在MainWindow中更改一些graphData属性,当我这样做时,图形将重新渲染,并且所有呈现都发生在控件而不是窗口内。 Ex: 例如:

<controls:GraphControl x:Name="GraphControl" GraphData="{Binding GraphData}"/>

If I create new DependencyProperty in Window, then all changes are handled in window, not control. 如果我在Window中创建新的DependencyProperty,则所有更改都在window中处理,而不是在控件中处理。

As far as I can understand, you want to bind a property of your control to a property on the window rather than on the DataContext. 据我了解,您想将控件的属性绑定到窗口上的属性,而不是DataContext上的属性。 If this is the case, you can achieve it using the RelativeSource attibute, like this: 在这种情况下,您可以使用RelativeSource外观来实现,如下所示:

<controls:GraphControl x:Name="GraphControl" GraphData="{Binding Path=GraphData, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM