【问题标题】:Binding using a relative source and dependency property - MVVM使用相对源和依赖属性进行绑定 - MVVM
【发布时间】:2013-02-07 21:13:40
【问题描述】:

谁能解释一下与 MVVM 绑定时的 Relativesource- 祖先特性。基本上,依赖属性通过视图模型绑定到具有上述概念的按钮。对样本进行一些解释会很棒。否则一些链接也可以。

编辑 1:

<Button Name="button1" Content ="Edit" Margin="0, 0, 5, 0" Style="{StaticResource button}"  
        Grid.Column="0" Visibility="{Binding cMode, Converter={StaticResource VisibilityConverter}, ConverterParameter={StaticResource invert}}"  
        Click="EditButton_Click"  
        IsEnabled="{Binding Path= Data.User.CanEdit, RelativeSource={RelativeSource FindAncestor, AncestorType=views:SCView, AncestorLevel=1}}"/>

CanEdit 也是一个依赖属性

【问题讨论】:

  • 你读过这个article吗?
  • 我已经阅读了,但我不是很清楚...
  • 你的DataContext是什么?从我所看到的情况来看,我认为您不需要 RelativeSource 绑定。
  • datacontext 在构造函数中设置为 Data

标签: c# wpf data-binding mvvm viewmodel


【解决方案1】:

它搜索元素 Ancestors,直到找到 AncestorType 的元素。该元素将被视为 Source。

在以下示例中,Button 将具有与 Grid 相同的宽度:

<Grid Width="100"> <!--Level=2-->
    <Border> <!--Level=1-->
        <Button Width="{Binding RelativeSource={RelativeSource AncestorType={x:Type Grid}}, Path=ActualWidth}"/>
    </Border>
</Grid>

此外,您可以通过设置 AncestorLevel 来设置要搜索的级别。

【讨论】:

  • 请检查我的编辑1。在那个祖先是否是 SCView 的 viewmodel ?
  • 试试这个:Path=DataContext.Data.User.CanEdit
  • 嗯...我可以看到一些不同。这种变化是什么意思?我的意思是我不明白这个变化会发生什么
  • 我假设属性Data 是您的ViewModel 的一部分,它是SCView 的DataContext。您可以通过 DataContext.Properties 访问它。如果 Data 是 ViewModel,则将行更改为 DataContext.User.CanEdit
  • Data是viewmodel,在构造函数中设置为SCView的DataContext。
猜你喜欢
  • 2014-04-10
  • 2013-02-07
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 2012-07-11
  • 2013-10-09
  • 2014-01-09
  • 1970-01-01
相关资源
最近更新 更多