Unset/Change Binding in WPF

Posted by captcalamares on Stack Overflow See other posts from Stack Overflow or by captcalamares
Published on 2013-07-01T09:08:51Z Indexed on 2013/07/01 10:21 UTC
Read the original article Hit count: 253

Filed under:
|
|
|

How can I unset the binding applied to an object so that I can apply another binding to it from a different location?

Suppose I have two data templates binded to the same object reference.

Data Template #1 is the default template to be loaded. I try to bind a button command to a Function1 from my DataContext class:

<Button Content="Button 1" CommandParameter="{Binding }" Command="{Binding DataContext.Function1, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>

This actually works and the function gets binded. However, when I try to load Data Template # 2 to the same object (while trying to bind another button command to a different function (Function2) from my DataContext class):

<Button Content="Button 2" CommandParameter="{Binding }" Command="{Binding DataContext.Function2, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />

It doesn't work and the first binding is still the one executed. Is there a workaround to this?

EDIT (for better problem context): I defined my templates in my Window.Resources:

<Window.Resources>
    <DataTemplate DataType="{x:Type local:ViewModel1}">
        <local:View1 />
    </DataTemplate>
    <DataTemplate DataType="{x:Type local:ViewModel2}">
        <local:View2 />
    </DataTemplate>
</Window.Resources>

The View1.xaml and the View2.xaml contain the button definitions that I described above (I want them to command the control of my process flow). ViewModel1 and ViewModel2 are my ViewModels that implement the interface IPageViewModel which is the type of my variable CurrentPageViewModel.

In my XAML, I binded ContentControl to the variable CurrentPageViewModel:

<ContentControl Content="{Binding CurrentPageViewModel}" HorizontalAlignment="Center"/>

In my .CS, I have a list defined as List<IPageViewModel> PageViewModels, which I use to contain the instances of my two View Models:

PageViewModels.Add(new ViewModel1());
PageViewModels.Add(new ViewModel2());

// Set starting page
CurrentPageViewModel = PageViewModels[0];

When I try to change my CurrentPageViewModel to the other view model, this is when I want the new binding to work. Unfortunately, it doesn't. Am I doing things the right way?

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf