如何正确使用datacontext多种方式

时间:2012-08-02 14:42:50

标签: windows-phone-7 wpf-controls

好的,所以我想使用颜色选择器,找到Alex Yakhnin的博客......

http://blogs.msdn.com/b/priozersk/archive/2010/09/17/customizing-picker-box-dialog.aspx

从博客实施此代码后

  DialogViewModel viewModel;
    PickerBoxDialog customDialog;
    ColorItem currentColorItem;

    private void InitCustomPickerDialog()
    {
        // Initialize viewmodel
        this.viewModel = new DialogViewModel();
        this.currentColorItem = viewModel.Items[0];

        // Assing it to the page's DataContext
        this.DataContext = currentColorItem;
        this.customDialog = new PickerBoxDialog();
        this.customDialog.Title = "ACCENTS";

        // Assign our style to the dialog
        this.customDialog.Style = this.Resources["Custom"] as Style;
        this.customDialog.ItemSource = viewModel.Items;
        this.customDialog.Closed += new EventHandler(customDialog_Closed);
    }
    void customDialog_Closed(object sender, EventArgs e)
    {
        this.currentColorItem = (ColorItem)this.customDialog.SelectedItem;
        this.DataContext = currentColorItem;
    }
    private void buttonColor_Click(object sender, RoutedEventArgs e)
    {
        this.customDialog.Show();
    }

我意识到页面的datacontext用于设置选择器的颜色。我在同一页面上使用了一个列表框,它也设置了页面的datacontext以显示一个fish列表。

 public FishsPage()
    {
        InitializeComponent();
        DataContext = App.vmFish;
        InitCustomPickerDialog();
    }

因此,我现在需要页面的datacontext用于2个不同的东西。有没有办法同时使用颜色选择器控件和鱼类列表?

Erno的建议?:

public class FishViewModelComplete : INotifyPropertyChanged
{
    private readonly ReefServiceClient wcfProxy;

    public FishViewModelComplete()
    {
        vmFish = new FishViewModel();
        vmDialog = new DialogViewModel();
    }

    private FishViewModel _vmFish;
    public FishViewModel vmFish
    {
        get
        {
            return _vmFish;
        }
        set
        {
            _vmFish = value;
        }
    }

    private DialogViewModel _vmDialog;
    public DialogViewModel vmDialog
    {
        get
        {
            return _vmDialog;
        }
        set
        {
            _vmDialog = value;
        }
    }

}

1 个答案:

答案 0 :(得分:1)

创建第三个ViewModel,它通过属性公开两个ViewModel并将适当的控件绑定到这些。