【问题标题】:How do I setup binding so that selected value of combobox in one control changes control template of a different control?如何设置绑定,以便一个控件中组合框的选定值更改不同控件的控件模板?
【发布时间】:2014-03-15 10:53:06
【问题描述】:

我有这样的东西... 第一个用户控件如下

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

第二个用户控件如下...请查看代码中大写 cmets 的位置。我想将 PrintBox 的控件模板设置为用户在 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>

感谢您的帮助!!!

【问题讨论】:

  • 你试过 ElemenetName="PrintTemplateComboBox" Path=SelectedValue 吗?
  • 谢谢,但在我的情况下这不起作用,因为这些控件不在同一个窗口/控件上

标签: c# wpf binding combobox


【解决方案1】:
  <Grid>
        <local:PrintBox x:Name="PrintBox"
                       Template="{Binding ElementName=PrintTemplateComboBox,Path=SelectedValue}"/>
  </Grid>

或者您可以使用转换器来确定您返回的内容

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

这是转换器

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

【讨论】:

  • 谢谢,但在我的情况下这不起作用,因为这些控件不在同一个窗口/控件上
  • 所以在这种情况下,您需要一个能够同时知道这两个控件的控制器。而且您可以将一个控件的选择更改事件注册到另一个控件,然后从那里在视图模型中设置绑定属性
猜你喜欢
  • 2014-08-15
  • 1970-01-01
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-06
  • 1970-01-01
相关资源
最近更新 更多