简体   繁体   English

DataTemplate作为具有可自定义绑定的资源

[英]DataTemplate as resource with customizable bindings

I have a DataTemplate that I use to present a value with symbol that looks something like this: 我有一个DataTemplate ,用于呈现带有符号的值,如下所示:

<DataTemplate>
    <TextBlock VerticalAlignment="Center">
        <TextBlock.Text>
            <MultiBinding StringFormat="{}{0:G} {1}">
                <Binding Path="DisplayValue" />
                <Binding Path="UnitSymbol" />
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>
</DataTemplate>

This template is repeated frequently in my XAML with different bindings (ie DisplayValue and UnitSymbol differs). 该模板在我的XAML中经常重复,具有不同的绑定(即DisplayValueUnitSymbol不同)。 I would like to create a DataTemplate as a resource and change the binding, eg something like ItemTemplate="{StaticResource MyUnitTemplate, ValuePath=DisplayValue, UnitPath=UnitSymbol}" . 我想创建一个DataTemplate作为资源并更改绑定,例如ItemTemplate="{StaticResource MyUnitTemplate, ValuePath=DisplayValue, UnitPath=UnitSymbol}" How can I achieve this? 我怎样才能做到这一点?

Note! 注意! I realize I could create a custom data type that holds a value with unit and create a template for this type, but I'm curious to if it is possible to use resources as mentioned above. 我意识到我可以创建一个自定义数据类型,它包含一个单位的值并为这种类型创建一个模板,但我很好奇是否可以使用上面提到的资源。

You can do exactly what you are looking for, and fairly easily. 你可以很容易地完成你正在寻找的东西。 First, put your DataTemplate in a resources dictionary somewhere (or you can put it in the Windows or UserControl Resources section). 首先,将DataTemplate放在某个地方的资源字典中(或者将其放在Windows或UserControl Resources部分中)。

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<DataTemplate x:Name="TextBoxStyle">
<TextBlock VerticalAlignment="Center">
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0:G} {1}">
            <Binding Path="DisplayValue" />
            <Binding Path="UnitSymbol" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Then, in your usercontrol, reference the resource library. 然后,在您的usercontrol中,引用资源库。

    <UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/SialTPChat.UI.Design;component/Styles/ResourceDic.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </UserControl.Resources>

Now you can use it anywhere in this usercontrol, and you can set the ItemsSource of the textbox to anything you want. 现在,您可以在此用户控件中的任何位置使用它,并且可以将文本框的ItemsSource设置为您想要的任何内容。 IE, IE浏览器,

   <TextBlock Style="{StaticResource TextBoxStyle}" /> //Set the ItemsSource to anything

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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