带有MVVM Light的数据绑定工具套件 [英] DataBinding with MVVM Light tool kit

查看:84
本文介绍了带有MVVM Light的数据绑定工具套件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用MVVM工具包进行绑定时遇到了一些麻烦,并且如果我做得正确,我会提醒一些建议.首先,我有一个View Model Locator,其定义如下:

I get some trouble with the binding using MVVM toolkit and would likr to knwo some advise if I do things correctly. First of all I have the View Model Locator which is defined as follow :

public class ViewModelLocator
{
    private static MainViewModel _main;
    private static ProductViewModel _product;

    /// <summary>
    /// Initializes a new instance of the ViewModelLocator class.
    /// </summary>
    public ViewModelLocator()
    {
        ////if (ViewModelBase.IsInDesignModeStatic)
        ////{
        ////    // Create design time view models
        ////}
        ////else
        ////{
        ////    // Create run time view models
        ////}

        CreateMain();
        CreateProduct();
    }

    /// <summary>
    /// Gets the Main property.
    /// </summary>
    public static MainViewModel MainStatic
    {
        get
        {
            if (_main == null)
            {
                CreateMain();
            }

            return _main;
        }
    }

    /// <summary>
    /// Gets the Main property.
    /// </summary>
    public static ProductViewModel ProductStatic
    {
        get
        {
            if (_product == null)
            {
                CreateProduct();
            }

            return _product;
        }
    }

    /// <summary>
    /// Gets the Main property.
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
        "CA1822:MarkMembersAsStatic",
        Justification = "This non-static member is needed for data binding purposes.")]
    public MainViewModel Main
    {
        get
        {
            return MainStatic;
        }
    }

    /// <summary>
    /// Gets the Main property.
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
        "CA1822:MarkMembersAsStatic",
        Justification = "This non-static member is needed for data binding purposes.")]
    public ProductViewModel Product
    {
        get
        {
            return ProductStatic;
        }
    }

    /// <summary>
    /// Provides a deterministic way to delete the Main property.
    /// </summary>
    public static void ClearMain()
    {
        _main.Cleanup();
        _main = null;
    }

    /// <summary>
    /// Provides a deterministic way to create the Main property.
    /// </summary>
    public static void CreateMain()
    {
        if (_main == null)
        {
            _main = new MainViewModel();
        }
    }

    /// <summary>
    /// Provides a deterministic way to create the Main property.
    /// </summary>
    public static void CreateProduct()
    {
        if (_product == null)
        {
            _product = new ProductViewModel();
        }
    }

    /// <summary>
    /// Cleans up all the resources.
    /// </summary>
    public static void Cleanup()
    {
        ClearMain();
    }
}

然后我在主窗口中将datacontext设置为: DataContext ="{Binding Source = {x:Static vm:ViewModelLocator.MainStatic}}""

Then I have my main window for which I set the datacontext as : DataContext="{Binding Source={x:Static vm:ViewModelLocator.MainStatic}}"

在主窗口中,我有一个列表框,该列表框将具有 ProductViewModel 的集合作为ItemSource定义,如下所示:

Inside my main window I have a list box which will have as ItemSource a collection of ProductViewModel define as follow :

 public class ProductViewModel : ViewModelBase
{

     SvcProduct.ProductServiceClient _clientSvc =new SvcProduct.ProductServiceClient() ;
     ObservableCollection<Product> _products = new ObservableCollection<Product>();


     public ObservableCollection<Product> Products
     {
         get { return _products; }
         set { _products = value; }
     }

    /// <summary>
    /// Initializes a new instance of the ProductViewModel class.
    /// </summary>
    public ProductViewModel()
    {
        ////if (IsInDesignMode)
        ////{
        ////    // Code runs in Blend --> create design time data.
        ////}
        ////else
        ////{
        ////    // Code runs "for real": Connect to service, etc...
        ////}
        _products=_clientSvc.GetProducts();

    }

    ////public override void Cleanup()
    ////{
    ////    // Clean own resources if needed

    ////    base.Cleanup();
    ////}
}

ProductViewModel在Products中返回列表框的集合.列表框中的每个项目都连接到一个ProductView,后者是一个userControl定义,如下所示:

ProductViewModel return in Products the collection for the listbox. Each item in the list box is connected to a ProductView which is a userControl define as follow :

<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:Solatys.Presentation.ViewModel"
mc:Ignorable="d"
x:Class="Solatys.Presentation.ProductView"
x:Name="UserControl"
d:DesignWidth="640" d:DesignHeight="480" Width="433" Height="319"
IsManipulationEnabled="True"
DataContext="{Binding Source={x:Static vm:ViewModelLocator.ProductStatic}}">

<Grid x:Name="LayoutRoot">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="144.3"/>
        <ColumnDefinition Width="0.64*"/>
        <ColumnDefinition Width="144.3"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="35" MaxHeight="35"/>
        <RowDefinition Height="130" MaxHeight="130"/>
        <RowDefinition Height="130" MaxHeight="130"/>
        <RowDefinition Height="24" MaxHeight="24"/>
    </Grid.RowDefinitions>
        <Image Source="Resources/beauté.jpg" Grid.Row="1" Stretch="UniformToFill" Grid.RowSpan="2" Grid.ColumnSpan="3"/>
    <TextBlock TextWrapping="Wrap" Grid.Column="1" Text="{Binding ProductName}" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="16" Foreground="White" FontFamily="Perpetua Titling MT" TextAlignment="Justify"/>
        <Border BorderBrush="Black" BorderThickness="0" Grid.Row="3" Grid.ColumnSpan="3">
            <Border.Background>
                <RadialGradientBrush>
                    <GradientStop Color="#00000000" Offset="1"/>
                    <GradientStop Color="#FF005E01"/>
                </RadialGradientBrush>
            </Border.Background>
            <TextBlock TextWrapping="Wrap" Text="Coup de Coeur" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" FontFamily="Perpetua" TextAlignment="Justify" FontSize="13.333"/>
        </Border>

        <Border Grid.Row="1" Grid.Column="0" Background="#7F000000" d:LayoutOverrides="Width">
            <TextBlock TextWrapping="Wrap"  Foreground="White" FontFamily="Perpetua" Margin="5"><Run Text="Type de produit"/><Run Language="fr-fr" Text=" : "/><LineBreak/><Run Language="fr-fr"/><LineBreak/><Run Language="fr-fr" Text="Produit de beauté Bio"/></TextBlock>
        </Border>

        <Border HorizontalAlignment="Right" Grid.Row="1" Grid.Column="2" Width="144.3" Height="130" Background="#7F000000">
            <TextBlock Margin="5" TextWrapping="Wrap" Foreground="White" FontFamily="Perpetua"><Run Text="Court descriptif"/><LineBreak/><Run/><LineBreak/><Run Language="fr-fr" Text="Ce nouveau produit reste notre coup de coeur pour ses propriétés naturelles ..."/></TextBlock>
        </Border>

        <Border HorizontalAlignment="Center" Grid.Row="2" Grid.Column="1" Width="144.3" Height="130" Background="#7F000000">
            <TextBlock TextWrapping="Wrap" Margin="5" Foreground="White" FontFamily="Perpetua"><Run Text="Caractéristiques du produit"/><Run Language="fr-fr" Text=" : "/><LineBreak/><Run Language="fr-fr"/><LineBreak/><Run Language="fr-fr" Text="- rajeunissant"/><LineBreak/><Run Language="fr-fr" Text="- vivifiant"/><LineBreak/><Run Language="fr-fr" Text="- prix attractif"/><LineBreak/><Run Language="fr-fr" Text="- produit contrôlé"/></TextBlock>
        </Border>

</Grid>

如上所示,DataContext设置为ViewModelLocator.ProductStatic,但显示诸如无法创建ViewModelLocator实例"之类的错误

As you can see the above the DataContext is set to ViewModelLocator.ProductStatic but it says an error like "Cannot create instance of ViewModelLocator"

由于该绑定似乎未运行,因为主窗口上的列表框为空

Due to that it seems that the binding is not operating as my list box is empty on my main Window

1-知道我为该错误做错了什么吗? 2-在我的场景中,由于集合是ProductViewModel的集合,我应该如何绑定ItemSource?

1- Any idea what I do wrong for that error? 2- In my scenario, how should I bind the ItemSource as the collection is a collection of ProductViewModel ?

致谢 serge

推荐答案

无法创建ViewModelLocator实例"通常表示在创建VM时出现了问题.尝试在_products = _clientSvc.GetProducts()上放置一个断点,然后调试代码.我很确定此方法出了点问题,并引发了异常,这也导致ViewModelLocator失败.

"Cannot create instance of ViewModelLocator" is typically a sign that something went wrong while the VMs were created. Try to put a breakpoint on _products=_clientSvc.GetProducts() then debug the code. I am pretty sure that something is going wrong in this method and an exception is thrown, which is causing the ViewModelLocator to fail too.

干杯, 洛朗(Laurent)

Cheers, Laurent

这篇关于带有MVVM Light的数据绑定工具套件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆