0

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.

0

1 Answer 1

1

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}}}"/> 
Sign up to request clarification or add additional context in comments.

4 Comments

+ there is no reason to create DependencyProperty in MainWindow class, you should just implement INotifyPropertychanged to bind data to your control.
@VadimMartynov You see, even with your code when I define new DependencyProperty in Window it becomes new instance and does not affect UserControl. I mean for example I change text inside Control by code in setter in Control code-behind, I put breakpoint there. When my form appears I reach this bp, but not when I set property in Window
Just to add to Leo's answer you need Mode=TwoWay, to actually make it work. But if you are going to use the same property twice, then don't create it twice, have an attach property instead.
Well yes actually "Mode=TwoWay" could be the default, depending on the property you're binding.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.