我创建了一个简单的 WPF
UserControl
,其中包含 ComboBox
,我想公开后者的 ItemsSource
属性以从父视图绑定集合。
这是xaml
<StackPanel>
<ProgressBar
IsIndeterminate="True"
Visibility="{Binding Path=IsLoading, RelativeSource={RelativeSource AncestorType=UserControl}, Converter={StaticResource BooleanToVisibilityConverter}}"
Height="2"/>
<ComboBox
ItemsSource="{Binding Path=Items, RelativeSource={RelativeSource AncestorType=UserControl}}"
Loaded="ComboBox_Loaded">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel
Orientation="Horizontal">
<TextBlock
Margin="{StaticResource ChildControlMargin}"
Text="{Binding Name}"
Style="{StaticResource ComboBoxItemTextStyle}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
这是其背后的代码
public partial class LoadingComboBox : UserControl
{
public event EventHandler ComboBoxLoaded;
public bool IsLoading
{
get => (bool)GetValue(IsLoadingProperty);
set => SetValue(IsLoadingProperty, value);
}
public ObservableCollection<INameIdEntity> Items
{
get => (ObservableCollection<INameIdEntity>)GetValue(ItemsProperty);
set => SetValue(ItemsProperty, value);
}
private void ComboBox_Loaded(
object sender,
RoutedEventArgs e)
{
if (ComboBoxLoaded != null)
{
ComboBoxLoaded(this, e);
}
}
public LoadingComboBox()
{
InitializeComponent();
}
public static readonly DependencyProperty IsLoadingProperty =
DependencyProperty.Register(
nameof(IsLoading),
typeof(bool),
typeof(LoadingComboBox),
new PropertyMetadata(false));
public static readonly DependencyProperty ItemsProperty =
DependencyProperty.Register(
nameof(Items),
typeof(ObservableCollection<INameIdEntity>),
typeof(LoadingComboBox),
new PropertyMetadata(null));
}
这里是我使用该用户控件并将
Items
属性绑定到 ObservableCollection
的地方。
<views:LoadingComboBox
Grid.Column="0"
Items="{Binding Agents}"
IsLoading="{Binding AgentsAreLoading}"
ComboBoxLoaded="Agents_ComboBox_Loaded"/>
IsLoading
ComboBoxLoaded
属性工作正常,但组合框未填充数据。
我发现了这个错误(如果它是一个错误,而不是我滥用框架的话)。
INameIdEntity
是一个接口(两个属性 Id 和 Name),我想我可以创建这个 UserControl
,其中包含 ComboBox
并在每个项目中显示 Name
。
因此只需用具体类型替换接口就可以解决绑定问题。
public partial class LoadingComboBox : UserControl
{
public event EventHandler ComboBoxLoaded;
public bool IsLoading
{
get => (bool)GetValue(IsLoadingProperty);
set => SetValue(IsLoadingProperty, value);
}
public IEnumerable<Agent> Items
{
get => (IEnumerable<Agent>)GetValue(ItemsProperty);
set => SetValue(ItemsProperty, value);
}
private void ComboBox_Loaded(
object sender,
RoutedEventArgs e)
{
if (ComboBoxLoaded != null)
{
ComboBoxLoaded(this, e);
}
}
public LoadingComboBox()
{
InitializeComponent();
}
public static readonly DependencyProperty IsLoadingProperty =
DependencyProperty.Register(
nameof(IsLoading),
typeof(bool),
typeof(LoadingComboBox),
new PropertyMetadata(false));
public static readonly DependencyProperty ItemsProperty =
DependencyProperty.Register(
nameof(Items),
typeof(IEnumerable<Agent>),
typeof(LoadingComboBox),
new PropertyMetadata(null));
}
我想现在真正的问题是我原来的计划是否可行,即创建一个绑定到界面的 UserControl。