Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ListBox不显示绑定数据_C#_Wpf_Xaml - Fatal编程技术网

C# ListBox不显示绑定数据

C# ListBox不显示绑定数据,c#,wpf,xaml,C#,Wpf,Xaml,在我的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}"/>

在我的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"};
       }
   }

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

<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"};
       }
   }
私有列表actionList;
公共int行动
{ 
获取{返回this.action;}
设置
{
行动=价值;
populateActionList();
} 
}
公开列表行动列表
{
获取{return actionList;}
设置{this.actionList=value;}
私有void populateActionList()
{
如果(this.action==0)
{
actionList=新列表{
“中文”,
“印第安人”,
“马来语”,
“印第安人”,
};
if(this.action==1)
{
actionList=新列表{
“狗”,
“猫”,
“猪”,
“马”,
“鱼”,
“狮子”};
}
}

当我执行打印行时,我的操作列表会更改,但列表框项未设置为我的操作列表。只想知道UI不更新的原因和原因吗?我在某个地方读到,您必须更改为DataContext和ObservableCollections,但我尝试了该选项,但仍然没有更新。有人知道原因吗?

ActionList
应为
可观察集合


您应该将窗口的
DataContext
设置为具有属性的对象
ActionList

将您的代码更改为以下内容,将实现您所期望的

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");
  }
}
private observeCollection\u actionList;
公共可观察收集操作列表{
获取{
如果(_actionList==null){
_actionList=新的ObservableCollection();
}
返回操作列表;
}
}
私有void populateActionList(){
如果(this.action==0){
ActionList.Clear();
行动清单。添加(“中文”);
行动清单。添加(“印度”);
行动清单。添加(“马来语”);
行动清单。添加(“印度”);
}
if(this.action==1){
ActionList.Clear();
行动列表。添加(“狗”);
行动列表。添加(“猫”);
行动清单。添加(“清管器”);
行动列表。添加(“马”);
行动列表。添加(“鱼”);
行动清单。添加(“狮子”);
}
}

我复制了您的所有代码,并在新的WPF应用程序中运行

要解决绑定问题,有两种方法:

第一:在主窗口上创建加载的事件,代码如下:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    DataContext = this;
    populateActionList();
}
这在我的应用程序中提供了以下内容:

第二:您也可以将其绑定到XAML中,如下所示:

在MainWindow.xaml中:

将以下内容添加到窗口标记:

DataContext=“{Binding RelativeSource={RelativeSource Self}}”

然后在构造函数中,确保在运行InitializeComponent()之前设置数据:


在您的情况下,如果需要,您也可以使用列表,因为您正在替换整个列表,而不是添加/删除单个项目。为此,您必须使用ObservableCollection,如Jehof所写,它会自动触发CollectionChanged事件(而不是PropertyChanged)对集合执行添加/删除/清除/替换操作时

要使代码正常工作,您需要更改两件事:

  • 在viewmodel中正确实现INotifyPropertyChanged。对于数据绑定的每个属性,需要在setter中触发PropertyChanged事件。请参阅下面的代码
  • 当您希望更新绑定时,不要更改私有的
    actionList
    字段,而是更改属性
    actionList
    ,因为更改字段时,不会触发PropertyChanged事件
  • 需要记住的是:您的UI将侦听其数据绑定到的属性的PropertyChanged和CollectionChanged事件。因此,如果您的UI未得到更新,则通常不会触发这些事件

    视图模型:

    public class ViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    
        // Masters
        private List<string> _masters = new List<string>() { "Actions 0", "Actions 1" };
        public List<string> Masters { get { return _masters; } set { _masters = value; OnPropertyChanged("Masters"); } }
    
        // Action
        private int action;
        public int Action { get { return this.action; } set { action = value; PopulateActionList(); OnPropertyChanged("Action"); } }
    
        // ActionList
        private List<String> actionList;
        public List<String> ActionList { get { return actionList; } set { this.actionList = value; OnPropertyChanged("ActionList"); } }
    
    
        private void PopulateActionList()
        {
            if (this.action == 0)
                this.ActionList = new List<String> { "Chinese", "Indian", "Malay", "Indian" };
            else if (this.action == 1)
                this.ActionList = new List<String> { "Dog", "Cats", "Pigs", "Horses", "Fish", "Lion" };
        }
    }
    
    公共类视图模型:INotifyPropertyChanged
    {
    公共事件属性更改事件处理程序属性更改;
    私有void OnPropertyChanged(字符串propertyName)
    {
    if(this.PropertyChanged!=null)
    PropertyChanged(这是新的PropertyChangedEventArgs(propertyName));
    }
    //大师
    私有列表_masters=new List(){“操作0”,“操作1”};
    公共列表母版{get{return{U Masters;}set{U Masters=value;OnPropertyChanged(“母版”);}
    //行动
    私人行动;
    public int Action{get{return this.Action;}set{Action=value;PopulateActionList();OnPropertyChanged(“Action”);}
    //行动清单
    私人清单行动清单;
    公共列表ActionList{get{return ActionList;}set{this.ActionList=value;OnPropertyChanged(“ActionList”);}
    私有void PopulateActionList()
    {
    如果(this.action==0)
    this.ActionList=新列表{“中文”、“印度文”、“马来文”、“印度文”};
    else if(this.action==1)
    this.ActionList=新列表{“狗”、“猫”、“猪”、“马”、“鱼”、“狮子”};
    }
    }
    
    将其更改为ObservableCollection并不能解决他的问题。他会替换属性ActionList的值,因此需要为属性ActionList引发PropertyChanged事件。您是对的:-)另一种方法是替换现有集合的内容,而不是创建新实例。嗨,谢谢您的回复,但如果我如果我使用ObservaleCollection,我没有错,它是否已经为自己的属性(即actionList)的更改引发PropertyChanged事件当您向
    ObservableCollection
    添加元素时,将引发
    属性更改
    ,但当您用另一个
    ObservableCollection
    实例替换属性值时,则不会引发该问题。您可以手动或清除并填充现有集合,而不是创建新集合。
    CollectionChanged
    将在集合上引发功能改变,而非
    P