c# - 在 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; }
}
解决方案
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)
推荐阅读
- c - 指针地址操作:C
- node.js - 如何从 node.js 中的 json 获取特定内容
- java - intellij ide 找不到类定义
- java - 我正在开发 JavaFX 应用程序,遇到了一个错误。谁能解释这种行为?
- java - 实现泛型接口的正确方法
- php - 在视图刀片 laravel 中显示数据
- ios - UIBezierPath 的 close() 函数不适用于 SKShapeNode
- android - 图像/矢量资源现在显示在 ListView CustomAdapter 中
- mapkit - 从人类可读的字符串创建 MKPlacemark/CLPlacemark
- go - 操作数中出现意外的“=”