【问题标题】:Binding a combobox to a List<string> in wpf将组合框绑定到 wpf 中的 List<string>
【发布时间】:2014-09-18 15:11:39
【问题描述】:

这是一个 Silverlight 应用程序。

我正在尝试将组合框绑定到字符串列表。它将显示我在加载应用程序之前存储在列表中的值,但我也有它,因此用户可以将字符串添加到列表中,并且这些更改不会反映在组合框中。我已经确认列表正在正确更新,只是组合框没有更新。

以下代码当前的方式是,当我在运行时更新列表然后单击组合框下拉菜单时,整个 silverlight 应用程序就会消失。它不会抛出任何我可以在 VS、调试输出或浏览器中看到的错误,包含 silverlight 应用程序的浏览器窗口只是变为空白。

 <UserControl x:Class="SilverlightSpeak.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:local="clr-namespace:SilverlightSpeak.ViewModels"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <UserControl.Resources>
        <local:MainViewModel x:Key="MainViewModel"/>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="White" HorizontalAlignment="Center" VerticalAlignment="Top" DataContext="{StaticResource MainViewModel}">
        <Grid.RowDefinitions>
            <RowDefinition Height="23*"/>
            <RowDefinition Height="21*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="193*"/>
            <ColumnDefinition Width="60*"/>
        </Grid.ColumnDefinitions>
        <Button Content="Add" Command="{Binding AddWordCommand}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Grid.Column="1"/>
        <TextBox Text="{Binding ModelSpeaker.newWord, Mode=TwoWay}" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <ComboBox  ItemsSource="{Binding ModelSpeaker.vocab, Mode=TwoWay}"  SelectedIndex="{Binding ModelSpeaker.nextWordToSpeak, Mode=TwoWay}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" Grid.Row="1"/>
        <Button Content="Speak" Command="{Binding SpeakWordCommand}" CommandParameter="{Binding ModelSpeaker.nextWordToSpeak}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Grid.Row="1" Grid.Column="1" Grid.RowSpan="2"/>

    </Grid>
</UserControl>

我在我的 xaml 中做错了什么吗?我在 MainViewModel 和 Speaker Model 类中实现了 INotifyPropertyChanged,并且在更新词汇时发送通知。我不知道如何解决这个问题。

提前感谢您的帮助。

【问题讨论】:

  • 使用ObservableCollection&lt;T&gt;,而不是List&lt;T&gt;。这实现了INotifyCollectionChanged,这是它工作所必需的。

标签: c# wpf xaml silverlight combobox


【解决方案1】:

为了在集合发生变化时获得更新,集合需要实现INotifyCollectionChangedList&lt;T&gt; 没有实现这一点,但 ObservableCollection&lt;T&gt; 实现了,并且就像 List 一样工作。

所以,请尝试将您的类型从 List&lt;string&gt; 更改为 ObservableCollection&lt;string&gt;

【讨论】:

  • 谢谢,这么简单的解决方案,我花了太多时间。
猜你喜欢
  • 1970-01-01
  • 2014-01-31
  • 2011-02-21
  • 1970-01-01
  • 2023-03-15
  • 2017-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多