使用MVVM Light工具包进行DataBinding

时间:2011-12-02 08:23:05

标签: mvvm-light mvvm-toolkit

我在使用MVVM工具包进行绑定时遇到了一些麻烦,如果我正确地做事,我会更喜欢一些建议。首先,我有View Model Locator,定义如下:

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}}”

在我的主窗口中,我有一个列表框,其中包含 ProductViewModel 的ItemSource集合,如下所示:

 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定义如下:

<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实例”

由于我的主窗口上的列表框为空,似乎绑定没有运行

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

问候 哔叽

1 个答案:

答案 0 :(得分:1)

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

干杯, 劳伦