【发布时间】:2018-09-24 15:29:05
【问题描述】:
当我在 MVVM Light 中遇到 RaisePropertyChanged 问题时,我正在处理一个我似乎无法弄清楚的问题。当我尝试为我的列表提出更改时,列表确实会更新,但上面选定的索引值也是如此。传递给我选择的索引的值似乎受按下哪个键来触发事件的影响(即,如果我按“BACKSPACE”,传递给设置器的值是“-1”,而如果我输入一个字母,传递的值为“0”)
我重新创建了一个纯粹演示问题的项目。下面是 MainVeiwModel 中的主要逻辑部分:
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
_testItems = new List<TestItem>()
{
new TestItem() { Name = "Test1" },
new TestItem() { Name = "Test2" }
};
}
public int SelectedIndex
{
get { return _selectedIndex; }
set
{
_selectedIndex = value;
RaisePropertyChanged("SelectedIndex");
RaisePropertyChanged("SelectedText");
RaisePropertyChanged("TestList");
}
}
public string SelectedText
{
get
{
return _testItems[_selectedIndex].Name;
}
set
{
_testItems[_selectedIndex].Name = value;
RaisePropertyChanged("TextList");
}
}
public List<string> TextList
{
get
{
_textList = new List<string>();
if (_testItems != null && _testItems.Count > 0)
{
foreach (TestItem item in _testItems)
_textList.Add(item.Name);
}
return _textList;
}
set { _textList = value; }
}
private int _selectedIndex;
private List<string> _textList;
private List<TestItem> _testItems;
}
我的 XAML:
<Window x:Class="RaisePropertyBug.MainWindow"
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:RaisePropertyBug"
mc:Ignorable="d"
DataContext="{Binding Source={StaticResource Locator}, Path=Main}"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ComboBox ItemsSource="{Binding TextList, UpdateSourceTrigger=PropertyChanged}"
SelectedIndex="{Binding SelectedIndex, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox Grid.Row="1" Text="{Binding SelectedText, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
对于上下文:我有一个 ComboBox,它列出了我拥有的项目集合中的名称。有一个编辑窗口,用户可以在其中更改这些项目的名称和其他属性。我的目标是在用户编辑值时更新 ComboBox 列表。在我的实际程序中,您可以对索引 0 处的项目执行此操作,但只要按下某个键并到达 RaisePropertyChanged() 区域,任何其他索引都会自动更改为 0。
【问题讨论】:
-
你能分享一下 xaml 部分吗?
-
您不需要为 ItemsSource 绑定 RaisePropertyChanged("TestList") 或 UpdateSourceTrigger=PropertyChanged - 列表永远不会更改值。
-
对不起,我忘了说,在实际程序中,也可以在用户界面中添加和删除列表。但是该功能按预期工作,因此我没有将其包含在此处。
标签: c# wpf mvvm mvvm-light