简体   繁体   中英

WPF bindings in window and user control

I have Control Library and WPF application. I need to create my custom control to vizualize graph. So I made GraphControl and set there custom attribute 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. 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. 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.

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. If this is the case, you can achieve it using the RelativeSource attibute, like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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