【发布时间】:2016-12-12 10:16:59
【问题描述】:
我有一个 UWP 应用程序,我将 ComboBox 绑定到字典。这是一种工作,除了一个问题。当我尝试在我的视图模型中设置绑定的 SelectedValue 时,ComboBox 重置为 null 状态。
我尝试在 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>
【问题讨论】:
标签: c# xaml combobox enums win-universal-app