WPF绑定棘手的问题
我需要一些帮助来实现一些数据绑定。My viewmodel公开以下属性:WPF绑定棘手的问题,wpf,Wpf,我需要一些帮助来实现一些数据绑定。My viewmodel公开以下属性: public List<string> ChosenFeatures {get;set;} public Dictionary<string, double> AllFeatureCosts {get;set;} public List ChosenFeatures{get;set;} 公共字典AllFeatureCosts{get;set;} “ChosenFeatures”将包含“AllFe
public List<string> ChosenFeatures {get;set;}
public Dictionary<string, double> AllFeatureCosts {get;set;}
public List ChosenFeatures{get;set;}
公共字典AllFeatureCosts{get;set;}
“ChosenFeatures”将包含“AllFeatureCosts”中的字典键子集
在视图中,我想呈现一系列文本块,每个文本块对应“ChosenFeatures”中的每个项目。这里有一个棘手的部分:-每个TextBlock的Text属性需要绑定到“AllFeatureCosts”字典中的一个值,使用“ChosenFeatures”中的字符串作为该字典项的键
如果有人能给我指点如何编写XAML来实现这一点,我将不胜感激。为数据提供一个视图模型,这就是首先使用MVVM的原因
class FeatureViewModel
{
public FeatureViewModel(MyViewModel aViewModel, string aKey)
{
mParent = aViewModel;
mKey = aKey
}
public string Value
{
get{return mParent.AllFeatureCosts[mKey];}
}
}
将viewmodels的集合添加到主viewmodel
public ObservableCollection<FeatureViewModel> Features{ get; set; }
从这里,您还可以在必要时,并且如果正确实现了InotifyPropertyChange,对FeatureViewModels进行任何更改。当然,您需要保持这些集合的同步,这可能需要做一些工作
当然,您的数据模板也需要一些调整
<DataTemplate DataType="{x:Type FeatureViewModel}">
<TextBlock Text="{Binding Value}"/>
</DataTemplate>
首先,我想你应该使用@Jay的方法,并制作
ChosenFeatures
字典
但是,您可以使用转换器
,并在绑定时像传递参数一样传递字典:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var key = (string)value;
var dictionary = (Dictionary<string, double>)parameter;
if (dictionary.ContainsKey(key))
return dictionary[key];
else
return null;
}
公共对象转换(对象值、类型targetType、对象参数、CultureInfo区域性)
{
var键=(字符串)值;
var dictionary=(dictionary)参数;
if(字典容器(键))
返回字典[键];
其他的
返回null;
}
不绑定“ChosenFeatures”而绑定“AllFeatureCosts”。我们知道它将显示完整的列表,然后我们可以编写一个简单的多绑定可见性转换器来显示选中的项目(在ChosenFeatures中)
注:
根据字典的大小,它可能会影响应用程序的性能…为什么不制作另一个
ChosenFeatures
而不是只携带一个键呢?@Jay AllFeatureCosts是一个用于驱动应用程序中各种视图的单件,其值将不断变化(通过b/g线程更新)。我希望我能在XAML中做我需要的事情,但我怀疑解决方案要么令人讨厌,要么不可能!相反,我想我可以让viewmodel订阅AllFeatureCosts上的更改事件,并更新ChosenFeatures中的值(正如您所建议的那样,这将是一个字典)。
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var key = (string)value;
var dictionary = (Dictionary<string, double>)parameter;
if (dictionary.ContainsKey(key))
return dictionary[key];
else
return null;
}