我需要使用自定义的ItemTemplate扩展ListBox,但是当我运行代码时,不会应用ItemTemplate吗?
<ListBox x:Class="ExtendedCheckedListbox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ExtListBoxPOC"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Description}" VerticalAlignment="Stretch" VerticalContentAlignment="Center" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
private YesNoModel YesNo = new YesNoModel();
{
DataContext = YesNo;
cbl.ItemsSource = YesNo;
}
我的主Window XAML使用名为cbl的控件,该控件在后面的代码中设置了ItemsSource:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ExtListBoxPOC"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<local:ExtendedCheckedListbox x:Name="cbl" HorizontalAlignment="Left" Height="300" Margin="10" VerticalAlignment="Top" Width="300"/>
</Grid>
</Window>
Model类是这样:
public class YesNoModel
{
public string Description { get; set; }
public int Value { get; set; }
}
我要在这里添加项目:
{
YesNo.Add(new YesNoModel() { Description = "Yes", Value = 1 });
YesNo.Add(new YesNoModel() { Description = "No", Value = 2 });
YesNo.Add(new YesNoModel() { Description = "N/A", Value = 3 });
}
ExtendedCheckedListbox视图后面的代码:
public class ExtendedCheckedListbox : ListBox
{
}
答案 0 :(得分:0)
您派生的ListBox只是忽略了XAML,因为您显然没有在任何地方调用InitializeComponent()
。
但是,从控件派生的通常方法是在Themes\Generic.xaml
中创建默认样式。在您的Visual Studio项目中添加一个“自定义控件”,并按如下所示对其进行修改:
public class ExtendedCheckedListBox : ListBox
{
static ExtendedCheckedListBox()
{
DefaultStyleKeyProperty.OverrideMetadata(
typeof(ExtendedCheckedListBox),
new FrameworkPropertyMetadata(typeof(ExtendedCheckedListBox)));
}
}
然后将生成的Themes\Generic.xaml
文件的内容更改为此:
<Style TargetType="local:ExtendedCheckedListBox">
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<CheckBox Content="{Binding Description}"/>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
有关详细信息,请参见Control Authoring Overview。