WPF中的两个绑定场景

1. 如何在诸如ListBox这样的项中绑定父类数据上下文。

<ListBox Grid.Row="1" ItemsSource="{Binding Entries}">
    <ListBox.ItemTemplate>
        <DataTemplate>
                <TextBlock Text="{Binding Name}" Grid.Row="0" />                
            <materialDesign:Card.ContextMenu>
                    <MenuItem Header="Action" Command="{Binding Source={StaticResource Locator},Path=Entries.BeginPing}" CommandParameter="{Binding }"/>
                </ContextMenu>
            </materialDesign:Card.ContextMenu>
    </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

在上述代码中,ListBox的ItemSource为某个集合,在其模板中绑定了集合实体成员的Name属性。假设存在这样一个需求,需要在个ListBoxItem上做统一的一项操作,比如检查、删除等,则需要为ListBoix的某个控件(比如按钮、右键菜单等)绑定一个父类的命令实例。蓝色的Xaml代码实现了这一点,因为它在ListBox.ItemSource的数据上下文之下,需要显示指明其绑定的DataContext。

<MenuItem Header="Action" Command="{Binding Source={StaticResource Locator},Path=Entries.BeginPing}" CommandParameter="{Binding }"/>

在本项目中,使用了GalaSoft的Mvvm方案,Locator为App的资源,其通过DI注入了大量的ViewModel实例。Entries为此XamlDataCotext的ViewModel实例名,其存储在Locator中。

在网络上,还有一些其他的使用RelativeSource的方法,但我没有实现成功。比如讲AscentType指定为父类Windows,依然没有找到Windows的DataContext。比如在Binding to alternate DataContexts[1]中,其实现为:

<Button Content="Remove" CommandParameter="{Binding}"
                        Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemsControl}}, Path=DataContext.RemoveItemCommand}"/>
            </DockPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

我按照其实现方式,并没有实现成功。可能是因为使用了第三方的XAML设计方案,中间夹杂着大量的特殊标签。

2. 诸如ListBox的子项绑定了集合中的一项,如何进行格式化。

ListBox Grid.Column="0" ItemsSource="{Binding ResultQueue}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Path=.,Converter={StaticResource pintConvert}}"></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

在上述Xaml中,ListBox绑定了ResultQueue集合,ListBoxItem显示集合中的每个成员。默认情况下<TextBlock Text="{Binding }}"></TextBlock>就可以绑定。如果要对其实现格式转换,则需要为其提供一个默认的占位符。

参考:

[1]Binding to alternate DataContexts, http://blogs.interknowlogy.com/2011/04/26/binding-to-alternate-datacontexts/

原文地址:https://www.cnblogs.com/jjseen/p/6150634.html