【发布时间】:2010-01-26 22:56:20
【问题描述】:
如果我解释一下为什么我需要这样做会更好。
这不是真实的例子,但在我的工作解决方案中,用户将从这样的关系组开始:
苹果 -> 红色 香蕉 -> 黄色
在应用程序中,在不同的屏幕(例如添加水果和添加颜色)中,它们可以添加新的水果/颜色。然后他们需要在我在这里构建的这个屏幕中链接这些,还需要能够改变关系。因此,我无法在 xaml 中定义硬编码列表,因为用户可以更改它。所以我需要加载这个列表,然后在 Comboboxes 中显示它。到目前为止,以下解决方案都无法实现这一目标。
对以下上下文中的 StaticResource 有疑问:
<toolkit:DataGridTextColumn Header="Name"
Binding="{Binding Name}"
Width="5*" />
<toolkit:DataGridComboBoxColumn Header="Color"
ItemsSource="{Binding Source={StaticResource AllColors}}"
SelectedValueBinding="{Binding Path=Color}"
TextBinding="{Binding Path=Color}"
Width="5*" />
AllColors 将被定义为:
<x:Array x:Key="AllColors"
Type="sys:String">
<sys:String>Orange</sys:String>
<sys:String>Yellow</sys:String>
</x:Array>
除了我真正想做的是以编程方式将 StaticResource 设置为字符串列表或数组。
那我该怎么做呢?
谢谢。
编辑 1
这是我尝试过的:
// find resource object
//var resource = (string[])Resources["Colors"];
var i = 0;
var colors = new string[] { };
foreach (var fruit in fruitList)
{
colors[i] = fruit.Color;
i++;
}
Resources["Colors"] = colors;
没用。
请帮忙。
编辑 2: 我的完整代码 - 应该让我更清楚地了解我如何以编程方式定义资源
<UserControl x:Class="Wpf.Screen"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit" xmlns:Wpf="clr-namespace:Wpf" MinHeight="300" MinWidth="300" Loaded="Screen_Loaded"
Name="Fruits">
<GroupBox>
<toolkit:DataGrid Name="dgFruits"
AutoGenerateColumns="False"
Margin="10"
ItemsSource="{Binding}">
<toolkit:DataGrid.Columns>
<toolkit:DataGridTextColumn
Binding="{Binding Name}"
Header="Fruit Name"
Width="5*"/>
<toolkit:DataGridComboBoxColumn Header="Color"
ItemsSource="{Binding Source={StaticResource AllColors1}}"
SelectedValueBinding="{Binding Path=Color}"
TextBinding="{Binding Path=Color}"
Width="5*" />
</toolkit:DataGrid.Columns>
</toolkit:DataGrid>
</GroupBox>
C#:
namespace Wpf
{
public partial class Screen
public ObservableCollection<Fruit> FruitCollection { get { return fruitCollection; } }
public Screen()
{
LoadFruitFile(); //this loads fruit into ObservableCollection<Fruit> fruitCollection
InitializeComponent();
}
private void Screen_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
var i = 0;
var colors = new string[] { };
foreach (var fruit in fruitList)
{
colors[i] = fruit.Color;
i++;
}
// define resource in the code
Resources["AllColors1"] = colors;
// show new values
var resource = (string[])Resources["AllColors1"];
if (resource != null)
foreach (var item in resource)
Console.WriteLine(item);
dgFruits.ItemsSource = FruitCollection;
}
【问题讨论】:
-
似乎是一个相当普遍的数据绑定需求,不明白为什么这么难实现!
-
您能解释一下为什么进行静态绑定很重要吗?为什么不绑定到代码隐藏文件中的属性?
-
如果我能弄清楚该怎么做就好了。我可以绑定到 List 或在代码隐藏中创建 ObservableCollection 并绑定到其中任何一个,但我不知道如何在代码隐藏中做到这一点。
标签: c# wpf data-binding datagrid