views:

18

answers:

1

Hello,

I am trying to add the contents of my textfile to listbox. Here is the code :-

This is my MainPage.xaml :-

<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:ec="http://schemas.microsoft.com/expression/2010/controls" x:Class="MVVMDemo.MainPage"
             xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
             xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.SL4"
             mc:Ignorable="d"
             Height="300"
             Width="300"
             >

    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Skins/MainSkin.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <DataTemplate x:Key="DataTemplate1">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="0.579*"/>
                        <ColumnDefinition Width="0.421*"/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Margin="0,0,0,4" TextWrapping="Wrap" Text="{Binding ContactName}" d:LayoutOverrides="Width, Height"/>
                </Grid>
            </DataTemplate>
        </ResourceDictionary>
    </UserControl.Resources>

    <UserControl.DataContext>
        <Binding Path="Main" Source="{StaticResource Locator}"/>
    </UserControl.DataContext>

    <Grid x:Name="LayoutRoot" AllowDrop="True" UseLayoutRounding="True">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Drop">
                <cmd:EventToCommand  Command="{Binding DragCustomerCommand}" PassEventArgsToCommand="True"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        <ListBox x:Name="lstCustomersName" Margin="8" ItemsSource="{Binding Customers}" ItemTemplate="{StaticResource DataTemplate1}" FontSize="24" FontFamily="Arial Unicode MS" FontWeight="Bold">

            <ListBox.Effect>
                <DropShadowEffect/>
            </ListBox.Effect>
        </ListBox>
    </Grid>
</UserControl>

This is MainViewModel.cs :-

using GalaSoft.MvvmLight;
using System.Collections.ObjectModel;
using System.Windows;
using GalaSoft.MvvmLight.Command;
using System.IO;

namespace MVVMDemo.ViewModel
{

    public class MainViewModel : ViewModelBase
    {
        private RelayCommand<DragEventArgs> dragCustomerCommand = null;
        private RelayCommand<DragEventArgs> DragCustomerCommand
        {
            get
            {
                return dragCustomerCommand;
            }
            set
            {
                dragCustomerCommand = value;

            }
        }

        public string Welcome
        {
            get
            {
                return "Welcome to MVVM Light!!!This is my firstDemo";
            }
        }
        private ObservableCollection<CustomersServiceRef.Customer> customers;
        public ObservableCollection<CustomersServiceRef.Customer> Customers
        {
            get
            {
                return customers;
            }
            set
            {
                customers = value;
                RaisePropertyChanged("Customers");
            }
        }

        public MainViewModel()
        {
            dragCustomerCommand = new RelayCommand<DragEventArgs>(e => {
                MessageBox.Show(e.Data.ToString());
                if (e.Data == null)
                    return;
                var files = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];
                var file = files[0];
                using (var stream = file.OpenRead())
                {
                    using(var reader = new StreamReader(stream)){
                         var Customer = new CustomersServiceRef.Customer() { ContactName = reader.ReadLine()};
                         Customers.Insert(0, Customer);
                    }

                }
            });
            var CustomerService = new CustomersServiceRef.CustomersServiceClient();
            if (IsInDesignMode)
            {
                // Code runs in Blend --> create design time data.
            }
            else
            {
                CustomerService.GetCustomersCompleted += (s, e) =>
                {
                    if (e.Error == null)
                    {
                        Customers = new ObservableCollection<CustomersServiceRef.Customer>(e.Result);
                    }
                };
                CustomerService.GetCustomersAsync();

            }
        }


    }
}

Why is the drop event not working on my grid? It accepts the textfile but the command doesn't fire and i don't get any messagebox.

Thanks in advance :)

A: 

Its difficult to tell why your command isn't working. You should start by investigating whether your command is binding correctly.

First, run your app and watch the Output window for any error messages. Also, you can try adding a test value converter with a breakpoint.

public class TestConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Debug.WriteLine("TestConverter.Convert(value := {0}, targetType := {1}, parameter := {2}, culture := {3})",
                        value, targetType, parameter, culture);
        return value; // Put Breakpoint Here!!
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Debug.WriteLine("TestConverter.ConvertBack(value := {0}, targetType := {1}, parameter := {2}, culture := {3})",
                        value, targetType, parameter, culture);
        return value;
    }
}

Add the above class to your project, put a breakpoint on the indicated line, then modify your MainPage.xaml to use the value converter.

<UserControl ...
             xmlns:yourapp="clr-namespace:YourApplicationNamespace"
             >
    <UserControl.Resources>
        <ResourceDictionary>
            <!-- other resource dict stuff removed for brevity -->
            <yourapp:TestConverter x:Key="_TestConverter" />
        </ResourceDictionary>
    </UserControl.Resources>
    <UserControl.DataContext>
        <Binding Path="Main" Source="{StaticResource Locator}"/>
    </UserControl.DataContext>
    <Grid x:Name="LayoutRoot" AllowDrop="True" UseLayoutRounding="True">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Drop">
                <cmd:EventToCommand Command="{Binding Path=DragCustomerCommand,
                                                      Converter={StaticResource _TestConverter}}"
                                    PassEventArgsToCommand="True"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        <ListBox x:Name="lstCustomersName" Margin="8" ItemsSource="{Binding Customers}" ItemTemplate="{StaticResource DataTemplate1}" FontSize="24" FontFamily="Arial Unicode MS" FontWeight="Bold">
            <ListBox.Effect>
                <DropShadowEffect/>
            </ListBox.Effect>
        </ListBox>
    </Grid>
</UserControl>

If your command is binding, then your breakpoint will be activated. If you don't get your breakpoint, that will tip you off that something else is wrong.

Matt Casto
@Matt Casto :- I finally found out that problem was i declared `RelayCommand` property to be private :p. Made it public and it worked :)
Ankit Rathod