开发者

Command databinding issues with UserControl - separating DataContext?

In a question I had posted before regarding databinding and UserControls, I was having 开发者_运维问答problems getting simple properties set so that I could change colors, size, etc. Kent gave me some great pointers and that worked great. I then authored a new UserControl, and using his advice, had that working great as well.

Now I'm at the next step -- databinding commands. My current structure looks like this:

Window --contains--> UserControlB --contains--> UserControlA

Now databinding properties in UserControlA work great, and my UserControlB exposes these same properties so that the Window can change UserControlA indirectly. The problem is that UserControlB's DataContext is set something like this:

<UserControl x:Name="root">
  <Grid DataContext="{Binding ElementName=root}">
  ...
    <Button Command="{Binding MyCommand}" />
  ...
  </Grid>
</UserControl>

But I want MyCommand to be bound to my ViewModel. I thought it wass possible to set the DataContexts separately, but how do I get the Buttons to point to my ViewModel in XAML?

I found a related post, but didn't sound like what I want to do. I want to create the ViewModel in code, not in XAML.


Your binding should look something like this:

<Button Command="{Binding Path=DataContext.MyCommand, RelativeSource={RelativeSource     Mode=FindAncestor, AncestorType={x:Type TypeOfYourControlWithViewModelDataContext}}"/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜