我想创建一个新的用户控件,它显示我自己的组合框。 (Combobox有自己的风格和其他东西......(稍后会出现))
usercontrol xaml文件:
<UserControl x:Class="WpfApplication1.MyCombobox"
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"
mc:Ignorable="d" d:DesignWidth="500"
Height="50">
<ComboBox Height="42" ItemsSource="{Binding Path=MyItems}"></ComboBox>
</UserControl>
文件后面的用户控制代码:
namespace WpfApplication1
{
public partial class MyCombobox
{
public MyCombobox()
{
InitializeComponent();
MyItems = new List<ComboBoxItem>();
}
public List<ComboBoxItem> MyItems { get; set; }
}
}
mainwindow xaml文件:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WpfApplication1="clr-namespace:WpfApplication1" WindowStartupLocation="CenterScreen"
Height="350"
Width="500"
>
<Grid>
<WpfApplication1:MyCombobox>
<WpfApplication1:MyCombobox.MyItems>
<ComboBoxItem Height="36">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="16" />
<RowDefinition Height="16" />
</Grid.RowDefinitions>
<TextBlock Text="Item Title 1" Grid.Row="0" FontWeight="Bold" />
<TextBlock Text="Item Description 1" Grid.Row="1" FontStyle="Italic" />
</Grid>
</Grid>
</ComboBoxItem>
<ComboBoxItem Height="36">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="16" />
<RowDefinition Height="16" />
</Grid.RowDefinitions>
<TextBlock Text="Item Title 2" Grid.Row="0" FontWeight="Bold" />
<TextBlock Text="Item Description 2" Grid.Row="1" FontStyle="Italic" />
</Grid>
</Grid>
</ComboBoxItem>
</WpfApplication1:MyCombobox.MyItems>
</WpfApplication1:MyCombobox>
</Grid>
</Window>
我希望我可以在主窗口中将组合文件添加到我的usercontrol中。像那样:
<WpfApplication1:MyCombobox.MyItems>
<ComboBoxItem Height="36">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="16" />
<RowDefinition Height="16" />
</Grid.RowDefinitions>
<TextBlock Text="Item Title 2" Grid.Row="0" FontWeight="Bold" />
<TextBlock Text="Item Description 2" Grid.Row="1" FontStyle="Italic" />
</Grid>
</Grid>
</ComboBoxItem>
<!-- more items... -->
</WpfApplication1:MyCombobox.MyItems>
UserControl组合框使用了在主窗口中传递的项目。
当我运行代码时,它只显示一个空的组合框
怎么了?
答案 0 :(得分:1)
这与您在Combobox中创建MyItems绑定的方式有关。
要使其正确定位代码隐藏中的MyItems属性,您可以执行以下操作:
public MyCombobox()
{
InitializeComponent();
MyItems = new List<ComboBoxItem>();
this.DataContext = this;
}