1
我正在嘗試使複選框顯示覆選框,並選中每個複選框將更新組合框的文本以顯示所有已檢查的內容。出於某種奇怪的原因,它僅適用於複選框中的第一項,它完全讓我感到困惑,原因何在。我有一個虛擬項目,是非常小的演示它...組合框與複選框
public partial class MainWindow : Window
{
public ObservableCollection<DataObject> Collection { get; set; }
#region Private Methods
public MainWindow()
{
InitializeComponent();
Collection = new ObservableCollection<DataObject>();
Collection.Add(new DataObject { Name = "item1" });
Collection.Add(new DataObject { Name = "item2" });
Collection.Add(new DataObject { Name = "item3" });
Collection.Add(new DataObject { Name = "item4" });
Collection.Add(new DataObject { Name = "item5" });
this.DataContext = Collection;
}
#endregion
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
CheckBox chk = sender as CheckBox;
DataObject data = chk.DataContext as DataObject;
if ((bool)chk.IsChecked)
data.CboItems.Add(data.Name);
else if (data.CboItems.Contains(data.Name))
data.CboItems.Remove(data.Name);
}
}
public class DataObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string Name { get; set; }
private string cbotext;
public string CBOText {
get
{
return cbotext;
}
set
{
cbotext = value;
FirePropertyChanged("CBOText");
}
}
public ObservableCollection<string> CboItems { get; set; }
private void FirePropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
public DataObject()
{
CboItems = new ObservableCollection<string>();
CboItems.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(CboItems_CollectionChanged);
}
void CboItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
string text = string.Empty;
foreach (string item in CboItems)
{
if (text == string.Empty)
text = item;
else
text += ", " + item;
}
CBOText = text;
}
}
和XAML中...
<ComboBox Text="{Binding CBOText}" Width="150" Height="30" ItemsSource="{Binding}" x:Name="cbo" HorizontalContentAlignment="Stretch" IsEditable="True" Margin="12,12,342,270">
<ComboBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Name}" Checked="CheckBox_Checked" Unchecked="CheckBox_Checked" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
我可以看到事件CBOText字符串得到正確設置和射擊的PropertyChanged,但除非它是第一個項目,否則組合框不會反映它。很奇怪,有什麼想法?