我试图通过使用列表填充带有复选框的列表框, 其中列表中的每个字符串代表一个复选框。 我尝试了很多东西,没有显示复选框列表。只是空白!
XAML:
<ListBox Height="200" ItemsSource="{Binding namelist}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding}" IsChecked="False"></CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C#:
public static Dictionary<string, int> MenuContent = new Dictionary<string, int>();
public static List<string> namelist = new List<string>();
// **ctor with FillM() inside**
private void FillM()
{
MenuContent.Add("לחם", 5);
MenuContent.Add("חלב", 5);
MenuContent.Add("ביצה", 10);
MenuContent.Add("סלט", 15);
MenuContent.Add("טוסט", 10);
MenuContent.Add("בשר", 20);
foreach (KeyValuePair<string, int> item in MenuContent)
{
namelist.Add(item.Key);
}
}
修改
得到了它:
XAML:
<ListBox Name="ListBox1" ItemsSource="{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding}" IsChecked="False" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C#:
public static BindingList<string> namelist { get; set; }
public MainWindow()
{
InitializeComponent();
FillM();
ListBox1.DataContext = namelist;
}
private void FillM()
{
MenuContent.Add("לחם", 5);
MenuContent.Add("חלב", 5);
MenuContent.Add("ביצה", 10);
MenuContent.Add("סלט", 15);
MenuContent.Add("טוסט", 10);
MenuContent.Add("בשר", 20);
MenuContent.Add("קינוח", 100);
namelist = new BindingList<string>();
foreach (KeyValuePair<string, int> item in MenuContent)
{
namelist.Add(item.Key);
}
}
谢谢你们!
答案 0 :(得分:2)
试试这个:
<CheckBox Content="{Binding}" IsChecked="False"></CheckBox>
答案 1 :(得分:2)
这是因为你没有属性,你有一个列表,你需要绑定到一个属性:
试试这个:
public static Dictionary<string, int> MenuContent = new Dictionary<string, int>();
// This was changed
public static List<string> namelist { get; set; }
// **ctor with FillM() inside**
private void FillM()
{
MenuContent.Add("לחם", 5);
MenuContent.Add("חלב", 5);
MenuContent.Add("ביצה", 10);
MenuContent.Add("סלט", 15);
MenuContent.Add("טוסט", 10);
MenuContent.Add("בשר", 20);
MenuContent.Add("קינוח", 100);
// this is to avoid a null reference when filling
namelist = new List<string>();
foreach (KeyValuePair<string, int> item in MenuContent)
{
namelist.Add(item.Key);
}
}
我的xaml:
<ListBox ItemsSource="{Binding namelist}" />
和你的结果:
Beteavon ....
为了排除您的列表框样式,我已粘贴您的xaml。这是结果:
尝试此操作:使用以下内容更改namelist
属性:
/// <summary>
/// The <see cref="NameList" /> property's name.
/// </summary>
public const string NameListPropertyName = "NameList";
/// <summary>
/// Sets and gets the NameList property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public List<string> NameList
{
get
{
return _nameList;
}
set
{
if (_nameList == value)
{
return;
}
RaisePropertyChanging(NameListPropertyName);
_nameList = value;
RaisePropertyChanged(NameListPropertyName);
}
}
private List<string> _nameList = new List<string>( );
在此方法中,将名称更改为NameList:
private void FillM()
{
///...
foreach (KeyValuePair<string, int> item in MenuContent)
{
NameList.Add(item.Key);
}
}
确保 XAML 指向NameList
而不是namelist