【发布时间】:2022-01-07 02:33:50
【问题描述】:
我正在尝试使用 Xaml 中的 Binding 使用数据集合 ObservableCollection 填充我的 Combobox ItemsSource,但我总是得到 Combobox ItemsSource null 。
WPF UserControl Cs 代码:(更新代码)
public ObservableCollection<User> users { get; set; }
public partial class MainWindow : Window
{
InitializeComponent();
User user1 = new User("Mariah", 15);
User user2 = new User("John", 19 );
users = new ObservableCollections<User>();
users.Add(user1);
users.Add(user2);
this.DataContext = this;
Console.WriteLine(ComboBoxUsers.Items.Count); // always 0
Console.WriteLine(ComboBoxUsers.ItemsSource); // always null
}
WPF UserControl Xaml 代码:(更新了我的代码)
<ComboBox SelectedIndex = "0" x:Name="ComboBoxUsers" ItemsSource="{Binding users, UpdateSourceTrigger=PropertyChanged}" FontFamily="Arial" FontSize="11" Grid.Row="3" Height="30" Margin="10,5,5,5">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<Image IsEnabled="False" Source="{Binding Image}"/>
<TextBlock x:Name="textblock" IsEnabled="False" Text="{Binding Name} />
</StackPanel>
<DataTemplate.Resources>
<Style TargetType="ComboBoxItem">
<Setter Property="IsEnable" Value="{Binding IsEnable}"/>
</Style>
</DataTemplate.Resources>
</DataTemplate>
</ComboBox.ItemTemplate>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem" BasedOn="{StaticResource {x:Type ComboBoxItem}}">
<Setter
Property="Visibility"
Value="{Binding IsHidden}" />
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
班级用户
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public User(string name, int age)
{
this.Name = name;
this.Age = age;
}
}
这个问题的根源是什么?
【问题讨论】:
-
我已经添加了,抱歉我的代码没有完成,我已经更新了我的问题
-
我已经将combobox的
ItemsSource设置为Users -
是的,我已经添加了这部分代码
ComboBoxUsers.ItemsSource = users;进行测试,也许我的问题不是很清楚,后面代码中的绑定(C# 代码)运行良好,但问题只出现在 xaml代码 -
另请注意,ItemsSource Binding 上的
UpdateSourceTrigger=PropertyChanged无效,应将其删除,即使 Binding 有效。 -
好的,但是我想先解决我的问题,请看更新