我有一个UWP应用程序,我将ComboBox绑定到词典。除了一个问题,这是有效的。当我尝试在视图模型中设置绑定的SelectedValue时,ComboBox将重置为空状态。
我尝试在WPF中做同样的事情,但它没有这个问题。在线查看,我发现this页面正是我正在使用WPF做的,但我无法在UWP上找到任何内容。
在更新绑定值时,我需要做什么才能使ComboBox不重置?
这是一个简化的例子。我正在使用PropertyChanged.Fody和MvvmLightLibs
查看型号:
[ImplementPropertyChanged]
public class ViewModel
{
public ICommand SetZeroCommand { get; set; }
public ICommand ShowValueCommand { get; set; }
public ViewModel()
{
SetZeroCommand = new RelayCommand(SetZero);
ShowValueCommand = new RelayCommand(ShowValue);
}
public Numbers Selected { get; set; } = Numbers.One;
public Dictionary<Numbers, string> Dict { get; } = new Dictionary<Numbers, string>()
{
[Numbers.Zero] = "Zero",
[Numbers.One] = "One",
[Numbers.Two] = "Two"
};
private async void ShowValue()
{
var dialog = new MessageDialog(Selected.ToString());
await dialog.ShowAsync();
}
private void SetZero()
{
Selected = Numbers.Zero;
}
public enum Numbers
{
Zero,
One,
Two
}
}
的Xaml:
<Page
x:Class="UwpBinding.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UwpBinding"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
DataContext="{Binding MainWindow, Source={StaticResource Locator}}">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ComboBox Margin="105,163,0,0" ItemsSource="{Binding Dict}" DisplayMemberPath="Value" SelectedValuePath="Key" SelectedValue="{Binding Selected, Mode=TwoWay}"/>
<Button Content="Show" Command="{Binding ShowValueCommand}" Margin="25,304,0,304"/>
<Button Content="Set to 0" Command="{Binding SetZeroCommand}" Margin="10,373,0,235"/>
</Grid>
</Page>
答案 0 :(得分:2)
我做了一个基本的演示并重现了你的问题。经过研究,我发现了问题:Combox.SelectedValue
不能与Enumeration
一起使用。
目前的解决方法是改为使用SelectedIndex
。
例如: 在您的ViewModel中更改如下代码:
public int Selected { get; set; } = 1;
...
private void SetZero()
{
Selected = 0;
}
...
private async void ShowValue()
{
Numbers tmp=Numbers.Zero;
switch (Selected)
{
case 0: tmp = Numbers.Zero;
break;
case 1:tmp = Numbers.One;
break;
case 2:tmp = Numbers.Two;
break;
}
var dialog = new MessageDialog(tmp.ToString());
await dialog.ShowAsync();
}