首页 > 解决方案 > 在 WPF 中将全局值传递给 DateTemplate

问题描述

我有以下带有 DataTemplate 的 ListView,它创建三个 TextBlocks 并使用来自 class 的数据填充每个条目Item

我想将每个 TextBlock 的宽度设置为与数组一起传递的ICollection<Item>某个值,作为每个条目都相同的值。使用下面的语法,Item必须为每个实例设置 GlobalWidth1 等的值。

有没有办法将宽度值作为ICollection<Item>WPF 中整个集合的全局值传递?

<ListView>
    <ListView.ItemTemplate>
        <DataTemplate>
            <WrapPanel>
                <TextBlock Text="{Binding Data1}" Width="{Binding GlobalWidth1}" />
                <TextBlock Text="{Binding Data2}" Width="{Binding GlobalWidth2}" />
                <TextBlock Text="{Binding Data3}" Width="{Binding GlobalWidth3}" />
            </WrapPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
public class Item
    {
        public string Data1 { get; set; }

        public string Data2 { get; set; }

        public string Data3 { get; set; }
    }

标签: c#wpf

解决方案


XAML您可以在文件本身中定义资源值并使用{StaticResource ...}.

xmlns:system="clr-namespace:System;assembly=System.Runtime"
...
<ListView>
   <ListView.Resources>
       <system:Double
           x:Key="GlobalWidth1">
           100
       </system:Double>
       <system:Double
           x:Key="GlobalWidth2">
           120
       </system:Double>
       <system:Double
           x:Key="GlobalWidth3">
           150
       </system:Double>
   </ListView.Resources>
   <ListView.ItemTemplate>
       <DataTemplate>
           <WrapPanel>
               <TextBlock Text="{Binding Data1}" Width="{StaticResource GlobalWidth1}" />
               <TextBlock Text="{Binding Data2}" Width="{StaticResource GlobalWidth2}" />
               <TextBlock Text="{Binding Data3}" Width="{StaticResource GlobalWidth3}" />
           </WrapPanel>
       </DataTemplate>
   </ListView.ItemTemplate>
</ListView>

您甚至可以在顶层定义这些App.Resources并从App.xaml.cs.

注意:如果您将这些添加到App.Resources您将需要从本地删除它们ListView.Resources

    public App()
    {
        //hardcode

        this.Resources.Add("GlobalWidth1", 100);
        this.Resources.Add("GlobalWidth2", 120);
        this.Resources.Add("GlobalWidth3", 150);

        //or perhaps define them in the global settings
        this.Resources.Add("GlobalWidth1", Settings.Default.GlobalWidth1);
        this.Resources.Add("GlobalWidth2", Settings.Default.GlobalWidth2);
        this.Resources.Add("GlobalWidth3", Settings.Default.GlobalWidth3);
    }

在此处输入图像描述

当然,如果你想使用绑定来保留它,你可以在Item类上添加静态属性:

public class Item
{
    public string Data1 { get; set; }

    public string Data2 { get; set; }

    public string Data3 { get; set; }

    public static double GlobalWidth1 => 100;
    public static double GlobalWidth2 => 120;
    public static double GlobalWidth3 => 150;
}

我个人建议保留它,XAML因为我发现它更有条理,可以将纯 UI 代码保留在View层中和ViewModel层外(如果您坚持使用 MVVM)


推荐阅读