【问题标题】:Silverlight Binding - CommandParameter to Parent (help remove an x:Name)Silverlight 绑定 - 父级的 CommandParameter(帮助删除 x:Name)
【发布时间】:2011-08-12 02:01:57
【问题描述】:

知道如何绑定到列表框而不是在下面的代码中使用 x:Name 吗?我在 ElementName=myList

使用 xname
<ListBox x:Name="myList" Grid.Row="1" Height="auto" ItemsSource="{Binding Path=ListItems}" ItemContainerStyle="{StaticResource StretchedItemContainerStyle}" ScrollViewer.VerticalScrollBarVisibility="Disabled" Background="Transparent">
    <wi:Interaction.Triggers>
        <wi:EventTrigger EventName="SelectionChanged">
            <wi:InvokeCommandAction Command="{Binding Source={StaticResource Locator}, Path=ViewModel.Command}" CommandParameter="{Binding SelectedItem, ElementName=myList}" />
        </wi:EventTrigger>
    </wi:Interaction.Triggers>
    <ListBox.ItemTemplate>

我真的不想在每次使用 InvokeCommandAction 时都为我的控件定义一个名称。注意:wi 是​​ SL4/WP7.1 的 Windows 交互性

谢谢!

【问题讨论】:

    标签: silverlight xaml data-binding windows-phone-7 command


    【解决方案1】:

    尝试绑定到“SelectedItem”,并完全消除传递 CommandParameter 的需要。不要忘记 Mode=TwoWay。在 ViewModel 中添加“SelectedListItem”INotifyPropertyChanged getter/setter 并绑定到该属性。

    <ListBox SelectedItem={Binding SelectedListItem, Mode=TwoWay} Grid.Row="1" Height="auto" ItemsSource="{Binding Path=ListItems}" ItemContainerStyle="{StaticResource StretchedItemContainerStyle}" ScrollViewer.VerticalScrollBarVisibility="Disabled" Background="Transparent">
        <wi:Interaction.Triggers>
            <wi:EventTrigger EventName="SelectionChanged">
                <wi:InvokeCommandAction Command="{Binding Source={StaticResource Locator}, Path=ViewModel.Command}" />
            </wi:EventTrigger>
        </wi:Interaction.Triggers>
        <ListBox.ItemTemplate>
    </ListBox>
    

    【讨论】:

    • 这行得通,但它的代码比我想要的多一点。希望有一种说法 CommandParameter="{Binding SelectedItem, ElementName={RelativeSource=Parent}"。
    • @John - Silverlight 4 不支持RelativeSource.FindAncestor。是的,这很糟糕,但这就是紧凑框架的方式。 vidalsasoon 的回答恰到好处,将使您的代码在未来更易于维护。
    【解决方案2】:

    我不确定这是否真的可行,所以当我怀疑并等待其他人回答时,我会推荐一种不同的方法。

    您可以使用附加行为来执行此操作,这是一种简单而整洁的方法,可以提供更简洁的代码。

    我在my blog 上发布了written about it,并为它发布了一个框架,即available on NuGet

    ListBox 需要的是SelectorExtension。如果您只想要代码,请看这里:SelectorExtension.cs。 (来源为 MIT 许可)

    这意味着您可以简单地将代码更改为以下内容:

    <ListBox ext:SelectorExtension.Command="{Binding Source={StaticResource Locator}, Path=ViewModel.Command}"
             Grid.Row="1"
             Height="Auto"
             ItemsSource="{Binding Path=ListItems}"
             ItemContainerStyle="{StaticResource StretchedItemContainerStyle}"
             ScrollViewer.VerticalScrollBarVisibility="Disabled"
             Background="Transparent">
        ...
    

    其中extxmlns:ext="clr-namespace:ToolkitExtensions;clr-assembly=ToolkitExtensions"

    【讨论】:

      猜你喜欢
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      相关资源
      最近更新 更多