简体   繁体   中英

How do I setup binding so that selected value of combobox in one control changes control template of a different control?

I have something like this... The first user control is as below

<UserControl x:Class="FirstControl">
    <UserControl.Resources>
        <ResourceDictionary x:Key="PrintTemplates>
            <ControlTemplate x:Key="PrintTemplateA">
               .....
            </ControlTemplate>
            <ControlTemplate x:Key="PrintTemplateB">
               .....
            </ControlTemplate>
        <ResourceDictionary/>
    </UserControl.Resources>
    <Grid>
        <ComboBox x:Name="PrintTemplateComboBox" 
                  ItemsSource="{StaticResource PrintTemplates}" />
    </Grid>
</UserControl>

The second user control is as below... please see where I have the uppercase comments in code. I want to set the control template of PrintBox to whatever the user chooses in the combobox in the FirstControl

<UserControl x:Class="SecondControl">
    <Grid>
        <local:PrintBox x:Name="PrintBox"
                        Template={Binding SelectedValue, Source= I WANT THIS TO BE PrintTemplateComboBox IN THE FirstControl />
    </Grid>
</UserControl>

Thanks for your help!!!

  <Grid>
        <local:PrintBox x:Name="PrintBox"
                       Template="{Binding ElementName=PrintTemplateComboBox,Path=SelectedValue}"/>
  </Grid>

or you can use a converter to be certain what you return back

    <UserControl.Resources>
        <Local:YourTemplateConverter x:Key="yourTemplateConverter"/>
    </UserControl.Resources>
    <Grid>
Template="{Binding ElementName=PrintTemplateComboBox,Path=SelectedValue,Converter={StaticResource yourTemplateConverter}}"
</Grid

and this is the converter

class YourTemplateConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
       //value is whwat YourTemplateConverter get from the other combobox
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM