Answer the question
In order to leave comments, you need to log in
How to set binding to UserControl from viewmodel?
Strange behavior of binding to two different dependency properties on the same object. There is a Game view model that has three properties - Red, Blue and Turn. The viewmodel is set to the DataContext. There is also a MageControl usercontrol installed by the Mage viewmodel. I bind one of the Game properties to MageControl.DataContext - everything works fine, the studio tells you which property to set from the viewmodel (Red or Blue).
<Window ...>
<Window.DataContext>
<game:Game/>
</Window.DataContext>
<local:MageControl DataContext="{Binding Red}"/> <!-- всё отлично работает -->
</Window>
public partial class MageControl : UserControl
{
public int Turn
{
get { return (int)GetValue(TurnProperty); }
set { SetValue(TurnProperty, value); }
}
public static DependencyProperty TurnProperty = DependencyProperty.Register("Turn", typeof(int), typeof(MageControl));
}
<Window ...>
<Window.DataContext>
<game:Game/>
</Window.DataContext>
<StackPanel>
<local:MageControl DataContext="{Binding Red}"/> <!-- привязка к DataContext отлично работает -->
<local:MageControl DataContext="{Binding Blue}" Turn="{Binding Turn}"/> <!-- привязка к Turn не работает! -->
</StackPanel>
</Window>
<local:MageControl DataContext="{Binding Red}"
Turn="{Binding Turn, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type game:Game}}}" /> <!-- работает -->
Answer the question
In order to leave comments, you need to log in
<Window ...>
<Window.DataContext>
<game:Game/>
</Window.DataContext>
<StackPanel>
<local:MageControl DataContext="{Binding Red}"/> <!-- привязка к DataContext отлично работает -->
<local:MageControl DataContext="{Binding Blue}" Turn="{Binding Turn}"/> <!-- привязка к Turn не работает! -->
</StackPanel>
</Window>
The intelligence in the studio sometimes does not work at all, sometimes it lies, sometimes it slows everything down wildly.
Therefore, I advise you to try to fill in the data according to logic, as it is written at the very top, to check whether it works like this. Snoop
helps a lot in debugging , plus the studio was able to sort of write about binding errors in Output.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question