Coding

WPF常用小技巧

2018-10-24  本文已影响4人  清水包哟

菜单项部分绑定

有时需要动态生成菜单,但是同一个菜单中不仅仅包含动态项,而且包含固定项。这个时候就不能对菜单的ItemsSource进行绑定,而需要通过下面代码中的部分绑定方法实现。

  1. 菜单
<Menu x:Name="Menu">
    <Menu.Resources>
        <!--先把要绑定的动态菜单列表绑定到一个视图源集合-->
        <CollectionViewSource x:Key="items" Source="{Binding ElementName=Menu,Path=DataContext.MenuItemsProperty}"></CollectionViewSource>
    </Menu.Resources>
    <MenuItem Header="demo">
        <MenuItem.ItemsSource>
            <CompositeCollection>
                <MenuItem Header="Item1"></MenuItem>
                <!--然后把视图源集合绑定到集合容器中,就能够根据集合的改变,使用容器模板自动生成MenuItem-->
                <CollectionContainer Collection="{Binding Source={StaticResource items}}"></CollectionContainer>
                <MenuItem Header="Item2"></MenuItem>
            </CompositeCollection>
        </MenuItem.ItemsSource>
    </MenuItem>
</Menu>
  1. 内容菜单
 <ContextMenu x:Key="Menu">
    <ContextMenu.Resources>
        <CollectionViewSource x:Key="Items" Source="{Binding Path=DataContext.ContextMenuItems,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContextMenu}}"></CollectionViewSource>
    </ContextMenu.Resources>
    <ContextMenu.ItemsSource>
        <CompositeCollection>
            <CollectionContainer Collection="{Binding Source={StaticResource Items}}"></CollectionContainer>
            <MenuItem Header="Item1"></MenuItem>
        </CompositeCollection>
    </ContextMenu.ItemsSource>
</ContextMenu>

XAML条件编译

代码中存在测试代码时,我们不想通过频繁的注释、取消注释来开关代码就会使用编译条件,在不同编译条件下选择性编译。 WPF的.xaml文件中同样可以,我们通过在'AssemblyInfo.cs'文件中增加编译预处理的代码,增一个xmls中的DEBUG预定义。然后再xaml中使用这个预定就可以了。

  1. AssemblyInfo.cs
// 编译预处理
#if DEBUG
[assembly: XmlnsDefinition("DEBUG", "YourNameSpace")]
#endif
  1. MainWindow.xaml
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:DEBUG="DEBUG"

...

<!--条件编译-->
<mc:AlternateContent>
    <mc:Choice Requires="DEBUG">
        <!--这里可放置条件满足时编译的控件-->
    </mc:Choice>
    <mc:Fallback>
        <!--这里可放置条件不满足时编译的控件-->
    </mc:Fallback>
</mc:AlternateContent>
上一篇 下一篇

猜你喜欢

热点阅读