【问题标题】:How to do a Binding of a SelectValue to the MVVM in a project in UWP?如何在 UWP 的项目中将 SelectValue 绑定到 MVVM?
【发布时间】:2019-02-26 08:21:32
【问题描述】:

我一直试图在 ViewModel 中捕获组合框的 SelectValue,但我不能。

这是我的代码

<ComboBox SelectedValue="{Binding TipoDoc, Mode=TwoWay}"/>

这是视图模型

private string tipodoc; 
public string TipoDoc 
{ 
    get => tipodoc; 
    set 
    { 
        tipodoc = value; 
        RaisePropertyChanged();
     } 
} 

我无法捕获组合框的值。

我做错了什么?谢谢

【问题讨论】:

  • 你应该认真阅读绑定 MVVM 和 NotifyPropertyChanged 周围有很多教程,但这可能会对你有所帮助 stackoverflow.com/questions/19632270/…
  • 你是否在 ComboBox 中设置了 ItemsSource?..

标签: c# binding uwp selectedvalue


【解决方案1】:

@Ashiq 的建议是正确的。您需要为 ComboBox 设置 ItemsSource。

我做了一个代码示例供你参考:

<Page.DataContext>
    <local:ViewModel></local:ViewModel>
</Page.DataContext>

<Grid>
    <ComboBox ItemsSource="{Binding source}" SelectedValue="{Binding TipoDoc, Mode=TwoWay}"/>
</Grid>
public class ViewModel : INotifyPropertyChanged
{
    private string tipodoc;
    public string TipoDoc
    {
        get => tipodoc;
        set
        {
            tipodoc = value;
            RaisePropertyChanged("TipoDoc");
        }
    }

    public ObservableCollection<string> source { get; set; }

    public ViewModel()
    {
        source = new ObservableCollection<string>();
        source.Add("item1");
        source.Add("item2");
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string PropertyName)
    {
        if (PropertyChanged!= null)
        {
            PropertyChanged(this,new PropertyChangedEventArgs(PropertyName));
        }
    }
}

然后,当您选择一项时,TipoDoc 属性值将被更改。

【讨论】:

    猜你喜欢
    • 2020-08-02
    • 2016-04-09
    • 2016-07-25
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多