gpt4 book ai didi

c# - ListBox 不显示绑定(bind)数据

转载 作者:行者123 更新时间:2023-11-30 19:43:18 25 4
gpt4 key购买 nike

在我的 Xaml 中我有这个,

<ComboBox x:Name="masterCB" HorizontalAlignment="Left" Margin="5,127,0,0" VerticalAlignment="Top" Width="106" Height="22" Background="White" ItemsSource="{Binding Masters}" FontSize="11" SelectedIndex="{Binding Action}"/>
<Label Content="Select Action:" HorizontalAlignment="Left" VerticalAlignment="Top" Height="26" Width="116" Margin="0,151,0,0" Background="{x:Null}" FontWeight="Bold"/>

<ListBox x:Name="actionBox" HorizontalAlignment="Left" Height="250" VerticalAlignment="Top" Width="116" Margin="5,177,0,0" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ItemsSource="{Binding ActionList}" AlternationCount="2" MouseDoubleClick="actionBox_DoubleClick">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Background="{x:Null}">
<TextBlock Text="{Binding}" TextTrimming="WordEllipsis" TextWrapping="Wrap" Height="40" FontSize="11" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="Silver"/>
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>

在我的数据类中我有这个,

private List<String> actionList;
public int Action
{
get{return this.action;}
set
{
action = value;
populateActionList();
}
}
public List<String> ActionList
{
get { return actionList; }
set { this.actionList = value; }
private void populateActionList()
{
if (this.action == 0)
{
actionList = new List<String> {
"Chinese",
"Indian",
"Malay",
"Indian",
};
if (this.action == 1)
{
actionList = new List<String> {
"Dog",
"Cats",
"Pigs",
"Horses",
"Fish",
"Lion"};
}
}

当我执行 printline 时,我的 actionList 发生了变化,但是 ListBox 项没有设置到我的 actionList。只想知道 UI 不更新的原因和原因?我在某处读到您必须更改为 DataContext 和 ObservableCollections,但我试过了,但它仍然没有更新。有谁知道为什么?

最佳答案

将您的代码更改为以下内容,将达到您的预期

private ObservableCollection<String> _actionList; 

public ObservableCollection<String> ActionList {
get {
if (_actionList == null) {
_actionList = new ObservableCollection<String>();
}

return actionList;
}
}

private void populateActionList(){
if (this.action == 0) {
ActionList.Clear();

ActionList.Add("Chinese");
ActionList.Add("Indian");
ActionList.Add("Malay");
ActionList.Add("Indian");
}

if (this.action == 1){
ActionList.Clear();

ActionList.Add("Dog");
ActionList.Add("Cats");
ActionList.Add("Pigs");
ActionList.Add("Horses");
ActionList.Add("Fish");
ActionList.Add("Lion");
}
}

关于c# - ListBox 不显示绑定(bind)数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15494963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com