问题
I try to make a customized ListView which fills each list item with some stuff and an initial Checkbox if desired. Currently no Checkbox is displayed so I guess my code of the ContentControl stuff is somehow erroneous.
<ListView xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ListView.View>
<GridView>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<!-- Each list item: [Checkbox] Label -->
<StackPanel Orientation="Horizontal">
<!-- The code for the optional check box -->
<ContentControl>
<ContentControl.Style>
<Style TargetType="ContentControl">
<Style.Triggers>
<DataTrigger Binding="{Binding IsCheckable}" Value="True">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<CheckBox IsChecked="{Binding Path=SomeProperty}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
<!-- The non-optional test label -->
<Label Content="Test Content" />
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</ListView.View>
</ListView>
The Code behind:
public partial class MyListView : ListView {
public MyListView () {
InitializeComponent();
}
public bool IsCheckable
{
get { return (bool)GetValue(IsCheckableProperty); }
set { SetValue(IsCheckableProperty, value); }
}
public static readonly DependencyProperty IsCheckableProperty =
DependencyProperty.Register(
"IsCheckable",
typeof(bool),
typeof(AppropriatenessWidget),
new UIPropertyMetadata(false));
}
回答1:
{Binding IsCheckable}
binds to the DataContext
not the control, use for example:
{Binding IsCheckable,
RelativeSource={RelativeSource AncestorType=local:MyListView}}
Also i doubt that this subclassing approach is such a good idea, this could easily be handled via an underlying DataContext
.
来源:https://stackoverflow.com/questions/12202294/how-to-conditionally-insert-a-checkbox-in-a-list-item-of-a-customized-listview