【问题标题】:MVVM: Binding Convertors with Strongly Typed DataContextMVVM:使用强类型 DataContext 绑定转换器
【发布时间】:2011-06-01 02:33:01
【问题描述】:

我非常需要一个想法;

这是困扰我的问题:

我有一个视图,名为“DropDownView” 我就是这样使用它的:

<control:DropDownView  DataContext="{Binding StronglyTypedViewModel}"/>

意思是,在父页面ViewModel中,我有一个类型的属性:StronglyTypedViewModel&lt;T&gt;

现在,当视图呈现时,这一切都按我的预期完美运行;

但是,DropDownView 中的这几行行为令人不安:

<ctrl:CustomDropDown x:Name="cc"
                                   ItemsSource="{Binding ControlData}"
                                   ItemTemplate="{Binding ControlItemTemplate}"
                                   SelectedItem="{Binding ControlSelectedItem, ConverterParameter={Binding ControlData}, Converter={Binding}, Mode=TwoWay}"
...

使用 SelectedItem Converter 属性集,我得到运行时异常:绑定错误... 没有它,我可以看到按预期填充的下拉值(自定义 ItemTemplate 已绑定),但是显示为 object.ToString()!

我有强类型的 ViewModel,这意味着我应该有强类型的 Converter,它在 ViewModel 中声明为:

public class SMOEntityProcessingViewModel<T> : CustomViewModelBase, IValueConverter
...
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)

但是,由于我在编译时不知道 ViewModel 的类型,所以我无法为 ViewModel 添加一个可以用于 Convertor 的 StaticResource...

感谢任何帮助... 谢谢

@devdigital

ObservableCollection<T> ControlData;
object ControlSelectedItem;
ControlItemTemplate = Helpers.XAML.Methods.GenerateDataTemplate("{Binding Path=" + _propertyToShow + "}");
---------generating this in VM constructor, _propertyToShow depends on the T

"<DataTemplate ");
"xmlns='http://schemas.microsoft.com/winfx/"
"2006/xaml/presentation' "
"xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' >"
"<TextBlock Text='" + _propertyToShow + "' />"
"</DataTemplate>"

我还不知道如何创建转换器,所以还在进行中...

如果您需要更多详细信息,请告诉我,或者我可以通过邮件发送一些小演示... 非常感谢您的关注...

【问题讨论】:

    标签: mvvm binding datacontext converter ivalueconverter


    【解决方案1】:

    您的视图模型应该只负责相关视图的表示逻辑。将转换器代码分离为新类型,然后您可以将其添加为适当的资源。此外,假设您的 CustomDropDown 类型派生自 ItemsControl,您可以使用 DisplayMemberPath 属性来设置在显示中使用基础数据绑定对象的哪个属性,或者如果您需要更多格式控制,您可以设置 ItemTemplate 属性。

    【讨论】:

    • 基本控件是AutoCompleteBox;如果 ValueMemberPath 已绑定->runtime ex.;如果 ValueMemberBinding 改为 -> 应用程序冻结;分离的 Converter 应该以某种方式知道传入的 Type 是什么以及要转换的 Property...我是否应该考虑将参数(dependencyproperty)传递给 DropDownView 并将它们绑定到 Converter 中?
    • 不看更多代码很难说。 ControlData 和 ControlSelectedItem 的类型是什么,ControlItemTemplate 是什么样的?如果您创建一个单独的转换器并发布完整的更新代码会很有帮助。
    猜你喜欢
    • 2010-11-23
    • 2015-06-05
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 2011-02-09
    • 2021-08-29
    相关资源
    最近更新 更多