And*_*y T 3 wpf xaml styling listboxitem staticresource
我在WPF中创建了一个ListBox样式,以便它呈现为一个复选框列表.
当我手动填充ListBox的项目时,样式工作完美.但是,当我将ListBox的ItemsSource绑定到静态资源(包含所需项目的ItemsControl)时,样式将被完全删除.
这是风格:
<Style x:Key="CheckBoxListStyle" TargetType="ListBox">
<Style.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Grid Margin="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<CheckBox IsChecked="{Binding IsSelected, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"/>
<ContentPresenter
Grid.Column="1"
Margin="2,0,0,0" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Style.Resources>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<WrapPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Background" Value="Transparent" />
</Style>
Run Code Online (Sandbox Code Playgroud)
这是ListBox的代码,它正确显示了样式:
<ListBox x:Name="ColumnsList"
Grid.Column="0"
Grid.Row="0"
Style="{StaticResource CheckBoxListStyle}"
BorderThickness="1">
<ListBox.Items>
<ListBoxItem>Test</ListBoxItem>
<ListBoxItem>Test2</ListBoxItem>
<ListBoxItem>Test3</ListBoxItem>
</ListBox.Items>
</ListBox>
Run Code Online (Sandbox Code Playgroud)
这是ListBox忽略样式的代码:
<ListBox x:Name="ColumnsList2"
Grid.Column="0"
Grid.Row="0"
Style="{StaticResource CheckBoxListStyle}"
BorderThickness="1"
ItemsSource="{Binding Source={StaticResource Test1}, Path=Items}">
</ListBox>
Run Code Online (Sandbox Code Playgroud)
希望有人可以提供帮助 - 我对这一切都很陌生并尝试了我能想到的一切,但我读过的所有内容都让我相信设置ItemsSource应该与手动设置项目具有相同的结果,所以我可以'看到为什么这不起作用的任何原因.
谢谢,
在
将Style.Resources更改为设置ItemContainerStyle
属性,它应该像魅力一样工作.
<Style x:Key="CheckBoxListStyle" TargetType="ListBox">
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Grid Margin="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<CheckBox IsChecked="{Binding IsSelected, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"/>
<ContentPresenter
Grid.Column="1"
Margin="2,0,0,0" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<WrapPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Background" Value="Transparent" />
</Style>
Run Code Online (Sandbox Code Playgroud)
在旧版本(SP1之前)中,当您Style
在Style中定义s时,将忽略其中一个样式.或者,您可以在父资源中设置样式资源.
希望这可以帮助!
归档时间: |
|
查看次数: |
2153 次 |
最近记录: |