0
votes

I have the following controls/views:

  • myControl containing a ContentControl and two ControlTemplates in the UserControl.Resources
  • Main application (Window) with an instance of myControl and a ToggleButton

I want to switch between my two ControlTemplates via the ToggleButton in the main application.

This should be very easy ... but I cannot find a proper way :S

1
Changing the Resource via code of the Unchecked/Checked event of the togglebuttonseveves
sth like: void ToggleButtonChecked() { myControl.Resources["ControlTemplate1"] = myControl.TryFindResource("ControlTemplate2"); }seveves
ohhh ... got it ... stupid me. var cc = ManagePicker.FindChild<ContentControl>("myControl", 0); var ctpl = ManagePicker.TryFindResource("ControlTemplate1") as ControlTemplate; cc.Template = ctpl;seveves

1 Answers

1
votes

A simpler solution is to bind to the content property of the content control and define datatemplates for each type of content.

<Window.Resources>

    <DataTemplate DataType="{x:Type local:MyType1}">
        <Border Background="Red" />
    </DataTemplate>

    <DataTemplate DataType="{x:Type local:MyType2}">
        <Border Background="Green" />
    </DataTemplate>

</Window.Resources>

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="24" />
    </Grid.RowDefinitions>
    <ContentControl Content="{Binding MyContent}" />
    <ToggleButton Grid.Row="1"
                  Content="Toggle"
                  IsChecked="{Binding IsChecked}" />
</Grid>

//DataContext
public bool IsChecked
{
  get { return isChecked_; }

  set 
  { 
    isChecked_ = value;
    NotifyPropertyChanged_("IsChecked");

    if (value)
      MyContent = new MyType1();
    else
      MyContent = new MyType2();
  }
}

public object MyContent
{
    get { return myContent_; }
    set 
    {
       myContent = value;
       NotifyPropertyChange_("MyContent");
    }

}