MVVM填充组合框(WinRT和C#)

时间:2015-02-18 19:22:07

标签: c# wpf mvvm winrt-xaml

我的XAML中有一个ComboBox。它填充了以下代码:

PopulateColors.cs

public class PopulateColors
{
    public ObservableCollection<ItemsColors> itemsColors { get; set; } 

    public PopulateColors()
    {
        this.itemsColors = new ObservableCollection<ItemsColors>();
        this.itemsColors.Add(new ItemsColors{ ItemColumn = "Blue", IdItemColumn = 0 });      
        this.itemsColors.Add(new ItemsColors{ ItemColumn = "Red", IdItemColumn = 1 }); 
        this.itemsColors.Add(new ItemsColors{ ItemColumn = "Pink", IdItemColumn = 2 });        
    }      
}

public class ItemsColors
{
    public string ItemColumn { get; set; }
    public int IdItemColumn { get; set; }
}

pagedemo.xaml.cs:

ClothingViewModel  ClothVM = null;

public pagedemo()
{
    this.comboColors.DataContext = new PopulateColors();
} 

protected override void OnNavigatedTo(NavigationEventArgs e)
{           
    ClothVM  = new   ClothingViewModel();
    ClothVM  =  ClothVM.GetData(1);
    this.DataContext =  ClothVM ;
    navigationHelper.OnNavigatedTo(e);
}

private void SaveButton_Click(object sender, RoutedEventArgs e)
{
    string result =  ClothVM .Save( ClothVM );
    if (result.Contains("OK"))
    {
        //to do
    }
}

pagedemo.xaml(XAML设计)

<TextBox x:Name="txtJersey" 
         Text="{Binding Jersey, Mode=TwoWay}"/>

<ComboBox Name="comboColors"
          ItemsSource="{Binding itemsColors}"
          DisplayMemberPath="ItemColumn"                                                 
          SelectedValuePath="ItemColumn"/>  

确定。项目在ComboBox中显示正常。

问题:

我需要使用MVVM模式将所选颜色保存在数据库的表中。但是怎么样?我有这个代码。但我不知道如何将其与ComboBox

相关联

型号:Clothing.cs

Public class Clothing
{
    public string Color { get; set; }
    public string Jersey { get; set; }
}

ViewModel:ClothingViewModel.cs

public class ClothingViewModel : ViewModelBase
{ 
    public string Save (ClothingViewModel cloth)
    {
        string result = string.Empty;
        using (var db = new SQLite.SQLiteConnection(App.DBPath))
        {
            string change = string.Empty;
            try
            {
                var existing = (db.Table<Clothing>().Where(
                    c => c.id == 1)).SingleOrDefault();
                if (existing!= null)
                {
                    existing.Color = cloth.Color;
                    existing.Jersey = cloth.Jersey;
                    int success = db.Update(existing);
                }                 
            }
            catch
            { }
        }       
    }

    private int id = 1;
    public int ID
    {
        get
        { return id; }
        set
        {
            if (id == value)
            { return; }
            id= value;                
            RaisePropertyChanged("ID");
        }
    }

    private string color = string.Empty;
    public string Color
    {
        get
        { return color; }
        set
        {
            if (color == value)
            { return; }
            color = value;
            isDirty = true;
            RaisePropertyChanged("Color");
        }
    }

    private string jersey = string.Empty;
    public string Jersey
    {
        get
        { return jersey; }
        set
        {
            if (jersey == value)
            { return; }
            jersey = value;
            isDirty = true;
            RaisePropertyChanged("Jersey");
        }
    }
}

1 个答案:

答案 0 :(得分:2)

实际上,有很多选择。让我们展示其中的几个。

1。使用Binding with RelativeSource查找具有适当DataContext的Ancestor

XAML的代码:

<!-- Please use Page instead of Window. -->
<Window>
    <StackPanel>
        <TextBox x:Name="txtJersey" 
                 Text="{Binding Jersey, Mode=TwoWay}"/>

        <!-- Use {x:Type Page} instead of {x:Type Window}. -->
        <ComboBox Name="comboColors" ItemsSource="{Binding itemsColors}"
                  DisplayMemberPath="ItemColumn"
                  SelectedValue="{Binding 
                      RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},
                      Path=DataContext.Color}"
                  SelectedValuePath="ItemColumn" />
    </StackPanel>
</Window>

2。使用带有ElementName的Binding到具有适当DataContext

的UI元素

XAML的代码:

<StackPanel>
    <TextBox x:Name="txtJersey" 
             Text="{Binding Jersey, Mode=TwoWay}"/>

    <ComboBox Name="comboColors" ItemsSource="{Binding itemsColors}"
              DisplayMemberPath="ItemColumn"
              SelectedValue="{Binding 
                  ElementName=txtJersey,
                  Path=DataContext.Color}"
              SelectedValuePath="ItemColumn" />
</StackPanel>

3。使用包含另一个ViewModel

的“one”ViewModel
public class ClothingViewModel : ViewModelBase
{
    private readonly PopulateColors colors = new PopulateColors();

    public PopulateColors Colors
    {
        get { return this.colors; }
    }

    ...
}

页:

// This is a Page (Window in case of using WPF).
public class ClothingWindow
{
    public ClothingWindow()
    {
        InitializeComponent();
        // Note: no need to set the DataContext for the ComboBox.
        DataContext = new ClothingViewModel();
    }
}

XAML的代码:

<StackPanel>
    <TextBox Text="{Binding Jersey, Mode=TwoWay}"/>
    <ComboBox ItemsSource="{Binding Colors.itemsColors}"
              DisplayMemberPath="ItemColumn"
              SelectedValue="{Binding Color}"
              SelectedValuePath="ItemColumn" />
</StackPanel>

参考

  1. Data Binding (WPF), MSDN
  2. Data Binding in WPF, John Papa, MSDN Magazine