Jarrette
Jarrette

Reputation: 1095

How to properly use datacontext multiple ways

OK, so I wanted to use a color picker and found Alex Yakhnin's blog...

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

after implementing this code from the blog:

  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();
    }

I realized that the page's datacontext is being used to set the colors for the picker. I am using a listbox on this same page which also sets the datacontext of the page to display a list of fish.

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

Therefore, I need the page's datacontext for 2 different things now. Is there a way to use the color picker control and the fish list simultaneously?

Erno's suggestion?:

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;
        }
    }

}

Upvotes: 0

Views: 352

Answers (1)

Emond
Emond

Reputation: 50672

Create a third ViewModel that exposes the two ViewModels through properties and bind the appropriate controls to these.

Upvotes: 1

Related Questions