0

我正在使用Silverlight 4MVVM模式。

我的视图模型有两个属性:

  • SomeProperty
  • MyCommand

SomeProperty是一个复杂的类型并且有很多子属性。MyCommand是用于处理来自 Button 的命令的属性。

我有一个带有 Grid 的子窗口(视图),LayoutRoot它绑定到SomeProperty视图模型的属性。

<Grid x:Name="LayoutRoot" DataContext="{Binding SomeProperty, Mode=TwoWay}">
    ...
</Grid>

但是,在 Grid 内部,我想将 Button 的Command属性绑定到MyCommand视图模型的属性:

<Button Command={Binding MyCommand} />

但这不起作用,因为MyCommand它是视图模型的属性,而不是视图模型属性的SomeProperty属性。(当我单击按钮时,它不会执行命令。)

任何人,有没有办法在 Silverlight 4 中使用数据绑定,这样我可以让容器 UI 元素DataContext显式设置其属性,但随后在容器内有一个不同的控件引用一个属性,该属性是 of 的兄弟(或父级或其他DataContext)包含控件?

我当前的解决方法是在视图的类中定义绑定,但我宁愿在 XAML 中使用它。

谢谢

4

3 回答 3

3

如果你给你的根元素(ChildWindow、UserControl 等等)一个名字,那么你可以使用 ElementName 来访问视图模型。

<UserControl x:Name="MyUserControl">
    <Grid x:Name="LayoutRoot" DataContext="{Binding SomeProperty, Mode=TwoWay}">
        <Button Command="{Binding MyCommand}" DataContext="{Binding DataContext, ElementName=MyUserControl}" />
    </Grid>
</UserControl>

Or, here's another way to do the same thing.

<UserControl x:Name="MyUserControl">
    <Grid x:Name="LayoutRoot" DataContext="{Binding SomeProperty, Mode=TwoWay}">
        <Button Command="{Binding DataContext.MyCommand, ElementName=MyUserControl}" />
    </Grid>
</UserControl>
于 2012-04-12T21:41:37.223 回答
0

您尝试将数据上下文添加到绑定?datacontext 必须指向您的视图模型,因为默认数据上下文是父控件或父数据上下文,在这种情况下是您的布局根。

看到这个

这个

我希望这会有所帮助。问候。

于 2012-04-12T20:45:53.600 回答
0

I use a version of the BindableProxy described in this post: http://weblogs.asp.net/dwahlin/archive/2009/08/20/creating-a-silverlight-datacontext-proxy-to-simplify-data-binding-in-nested-controls.aspx

Above your Grid (probably within the UserControl.Resources) you would create:

<UserControl.Resources>
    <ns:BindableProxy x:Key="BindableProxy" />
<UserControl.Resources>

Then, in the button binding:

<Button Command="{Binding DataSource.MyCommand, Source={StaticResource BindableProxy}}" />
于 2012-04-13T01:41:57.927 回答