不能在WinRT MVVM中执行按钮单击和组合框选择更改
本文关键字:组合 选择 单击 按钮 WinRT MVVM 执行 不能 | 更新日期: 2023-09-27 18:02:36
UPDATE 1:您可以从这里下载示例项目。
你能帮我找出我代码中的错误吗?我无法将项目源分配到组合框以及WinRT应用程序中的按钮单击事件。我使用MVVM和MetroEventToCommand。我是MVVM概念的新手,所以请回答我的愚蠢问题。
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Button Content="Click Here">
<mvvm:EventToCommandManager.Collection>
<mvvm:EventToCommand Command="{Binding ButtonClickCommand}" Event="Click"/>
</mvvm:EventToCommandManager.Collection>
</Button>
<ComboBox x:Name="FontsCombo" Height="50" Width="150" SelectedItem="{Binding SelectedFont}" ItemsSource="{Binding fonts}" />
<TextBlock FontSize="30" Text="{Binding SelectedFont}"/>
</Grid>
public MainPage()
{
this.InitializeComponent();
this.DataContext = new VM();
}
public class VM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public RelayCommand ButtonClickCommand { get; set; }
private ObservableCollection<string> _fonts = new ObservableCollection<string>();
public ObservableCollection<string> fonts
{
get { return _fonts; }
set
{
_fonts = value;
if (null != PropertyChanged)
{
PropertyChanged(this, new PropertyChangedEventArgs("fonts"));
}
}
}
private string _SelectedFont = "";
public string SelectedFont
{
get { return _SelectedFont; }
set
{
// Some logic here
_SelectedFont = value;
if (null != PropertyChanged)
{
PropertyChanged(this, new PropertyChangedEventArgs("SelectedFont"));
}
}
}
public VM()
{
fonts.Add("Arial");
fonts.Add("Courier New");
fonts.Add("Times New Roman");
ButtonClickCommand = new RelayCommand(Click);
}
private void Click()
{
new Action(async () => await new Windows.UI.Popups.MessageDialog("Testing dialog").ShowAsync()).Invoke();
}
}
对于SelectedItem,您没有指定Mode=TwoWay:
<ComboBox x:Name="FontsCombo" Height="50" Width="150" SelectedItem="{Binding SelectedFont, Mode=TwoWay}" ItemsSource="{Binding fonts}" />
编辑我找到了解决方案:
public class VM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public RelayCommand ButtonClickCommand { get; set; }
private ObservableCollection<string> _fonts;
public ObservableCollection<string> fonts
{
get { return _fonts; }
set
{
_fonts = value;
if (null != PropertyChanged)
{
PropertyChanged(this, new PropertyChangedEventArgs("fonts"));
}
}
}
private string _SelectedFont;
public string SelectedFont
{
get { return _SelectedFont; }
set
{
// Some logic here
_SelectedFont = value;
if (null != PropertyChanged)
{
PropertyChanged(this, new PropertyChangedEventArgs("SelectedFont"));
}
}
}
public VM()
{
this.fonts = new ObservableCollection<string>();
fonts.Add("Arial");
fonts.Add("Courier New");
fonts.Add("Times New Roman");
ButtonClickCommand = new RelayCommand(Click);
}
private void Click()
{
new Action(async () => await new Windows.UI.Popups.MessageDialog("Testing dialog").ShowAsync()).Invoke();
}
}
如果我在构造函数中实例化字体,用户体验将不再冻结。