我有一个组合框:
<Grid>
<ComboBox Height="52" HorizontalAlignment="Left"
ItemsSource="{Binding templatesNames}"
SelectedValuePath="Type.FullName"
Margin="169,43,0,0" Name="comboBox1"
VerticalAlignment="Top" Width="148" />
<Button Content="Button"
***Template="{Binding key = Converter={Binding SelectedItem.Value,ElementName=comboBox1}}"
Height="56" HorizontalAlignment="Left"
Margin="191,204,0,0" Name="button1"
VerticalAlignment="Top" Width="80" />
</Grid>
问题是使用 * 签署的 我有templatesNames如何保存模板的名称 我想将这些名称转换为按钮即将绑定到的键(模板键)
我该怎么办?... 转换器应该做什么?它需要吗?我可以不用吗?
编辑: 这就是我现在所做的:
<ComboBox x:Name="ComboBox1"
ItemsSource="{Binding collection}"
Margin="553,0,0,13"
SelectedValuePath="Type.FullName" SelectedIndex="1"
FontFamily="Buxton Sketch"
FontSize="20" HorizontalAlignment="Left" Width="231" Height="46" VerticalAlignment="Bottom" />
其中集合是公共的ObservableCollection集合{get;组; }
按钮是@Meleak Button的similer,项目命名空间是clr-namespace:dinamicGridLayout 我应该在转换器内写入Uri resourceLocater = new Uri(@“clr-namespace:dinamicGridLayout; ResourceDictionary1.xaml”,System.UriKind.Relative);?
答案 0 :(得分:1)
如果您将所有ControlTemplates放在资源字典中,您可以像这样使用转换器来模板
<ComboBox Height="52" HorizontalAlignment="Left"
ItemsSource="{Binding templatesNames}"
SelectedValuePath="Type.FullName"
Margin="169,43,0,0" Name="comboBox1"
VerticalAlignment="Top" Width="148" />
<Button Content="Button"
Template="{Binding SelectedItem.Value,
ElementName=comboBox1,
Converter={StaticResource TemplateConverter}}"
Height="56" HorizontalAlignment="Left"
Margin="191,204,0,0" Name="button1"
VerticalAlignment="Top" Width="80" />
在转换器中,您从资源字典加载ControlTemplate并将其返回。
public class TemplateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string resourceKey = value.ToString();
Uri resourceLocater = new Uri("/YourNamespace;component/Dictionary1.xaml", System.UriKind.Relative);
ResourceDictionary resourceDictionary = (ResourceDictionary)Application.LoadComponent(resourceLocater);
return resourceDictionary[resourceKey] as ControlTemplate;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
<强>更新强>
如果您的命名空间是dinamicGridLayout,那么转换器应该如下所示
Uri resourceLocater = new Uri("/dinamicGridLayout;component/Dictionary1.xaml", System.UriKind.Relative);
小样本项目已上传here。