【发布时间】:2019-01-23 16:23:18
【问题描述】:
我需要使用自定义 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;
}
我的主窗口 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>
模型类是这样的:
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
{
}
【问题讨论】:
-
您是从代码中为 ListBox 设置 Itemsource 还是根本不设置?
-
从代码中是的,但我只是得到一个(集合)列表
-
描述是依赖属性吗?
-
请提供C#代码
-
您可以编辑代码部分并将其添加到问题中