1

I have a listview which I have binded (twoWay) to a datatable. The binding works fine and data is coming up properly on the listview. Now what I want to achieve is a bit complex and I am not even sure whether this can be achieved or now.

My datatable has say 15 columns, and I am showing 5 columns in the lisview. Is it possible that if the user selects a row on listview, I could display other 10 values for that selected row (from the datatable) in textblocks in stackpanel. Is this achievable or am I being too demanding? I tried to achieve this by getting ideas from question here, but couldn't achieve that. If it is achievable, can you guys give me ideas on how to proceed with this?

I think this might be achievable by handling listview1_selectionChanged event and populating the textboxes manually, but as I am in a learning stage, I wanted to explore if this can be done through databinding. This way I will know various ways of doing things and can build my concepts in the process.

I am attaching my code below. This is just a test project with one listview having one column.

XAML:

<Window.Resources>
    <Prefs:Tables x:Key="TClass"></Prefs:Tables>
</Window.Resources>
<Grid>
    <StackPanel Orientation="Horizontal">
        <ListView Name="listView1" Background="Transparent" Height="534" BorderThickness="0 0 0 1" VerticalAlignment="Top">
            <ListView.ItemsSource>
                <Binding Source="{StaticResource TClass}" Path="Instance.dtAccounts" Mode="TwoWay"></Binding>
            </ListView.ItemsSource>
            <ListView.View>
                <GridView x:Name="GridView1" ColumnHeaderContainerStyle="{StaticResource GridViewHeader}" AllowsColumnReorder="True">
                    <GridViewColumn Header="Company Name">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock x:Name="txbName" Padding="0 0 5 0" >
                                    <TextBlock.Text>
                                    <Binding Path="NAME">

                                    </Binding>
                                        </TextBlock.Text>
                                </TextBlock>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
        <StackPanel Name="stkPanel1" Margin="100 0 0 0">
            <TextBlock></TextBlock>
        </StackPanel>
    </StackPanel>
</Grid>

Window1.xaml.cs

public partial class Window1 : Window
{
    DataTable dt = new DataTable();
    public Window1()
    {
        InitializeComponent();
        Tables.Instance.dtAccounts = Worker.LoadAccounts();
    }

}

Class Tables.cs

public class Tables : INotifyPropertyChanged
{
    private static Tables instance;
    public event PropertyChangedEventHandler PropertyChanged = delegate { };
    private DataTable _dtAccounts;

    public Tables()
    {
    }

    // Singleton instance read-only property
    public static Tables Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Tables();
            }
            return instance;
        }
    }

    public DataTable dtAccounts
    {
        get
        {
            return _dtAccounts;
        }
        set
        {
            _dtAccounts = value;
            OnPropertyChanged("dtAccounts");
        }
    }

    private void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    } 
}

=====================

Final Working Code

I was able to do that with the help of answer provided by Phil. Posting my updated code below, as it might be useful for somebody else.

XAML:

<Grid>
    <StackPanel Orientation="Horizontal">
        <ListView Name="listView1" Background="Transparent" Height="534" BorderThickness="0 0 0 1" VerticalAlignment="Top" SelectionChanged="listView1_SelectionChanged">
            <ListView.ItemsSource>
                <Binding Source="{StaticResource TClass}" Path="Instance.dtAccounts" Mode="TwoWay"></Binding>
            </ListView.ItemsSource>
            <ListView.View>
                <GridView x:Name="GridView1" ColumnHeaderContainerStyle="{StaticResource GridViewHeader}" AllowsColumnReorder="True">
                    <GridViewColumn Header="Company Name">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <TextBlock Name="txbName" Padding="0 0 5 0" >
                                    <TextBlock.Text>
                                    <Binding Path="NAME">

                                    </Binding>
                                        </TextBlock.Text>
                                </TextBlock>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
        <StackPanel Name="stkPanel1" Margin="100 0 0 0">
            <TextBlock>
                <TextBlock.Text>
                    <Binding Source="{StaticResource TClass}" Path="Instance.SelectedName" Mode="TwoWay">

                    </Binding>
                </TextBlock.Text>
            </TextBlock>
        </StackPanel>
    </StackPanel>
</Grid>

Window1.xaml.cs

public partial class Window1 : Window
{
    DataTable dt = new DataTable();
    public Window1()
    {
        InitializeComponent();
        Tables.Instance.dtAccounts = Worker.LoadAccounts();
    }

    private void listView1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ListView lstView = sender as ListView;
        int item = lstView.SelectedIndex;
        Tables.Instance.SetSelectedRow(item);
    }
}

Tables.cs

public class Tables : INotifyPropertyChanged
{
    private static Tables instance;
    public event PropertyChangedEventHandler PropertyChanged = delegate { };
    private DataTable _dtAccounts;
    private string _selectedName;

    public Tables()
    {
    }

    // Singleton instance read-only property
    public static Tables Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Tables();
            }
            return instance;
        }
    }

    public DataTable dtAccounts
    {
        get
        {
            return _dtAccounts;
        }
        set
        {
            _dtAccounts = value;
            OnPropertyChanged("dtAccounts");
        }
    }

    public string SelectedName
    {
        get
        {
            return _selectedName;
        }
        set
        {
            _selectedName = value;
            OnPropertyChanged("SelectedName");
        }

    }

    public void SetSelectedRow(int index)
    {
        int indexNo = index;
        SelectedName = dtAccounts.Rows[index][0].ToString();
    }

    private void OnPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    } 
}
Community
  • 1
  • 1
Abhishek Jain
  • 2,957
  • 23
  • 35

2 Answers2

1

Here is a basic description of a way you can achieve this. This is not an ideal solution, but should get you on the right track.

  1. Create a field variable in your Tables class that represents a single row in your datatable.
  2. Create a method in your Tables class that sets that field variable to the proper row in your table.
  3. Create properties that expose the values of the row.
  4. Step #2's method will need to do change notification for all the properties exposed in Step #3 (OnPropertyChanged).
  5. Handle the selection_changed event in your code behind, and from that event handler call the method in your Tables class that sets the selected row.
  6. Bind your text blocks to the properties exposed in Step #3.
Phil Sandler
  • 27,544
  • 21
  • 86
  • 147
  • Thanks Phil, it worked perfectly well. I will paste the updated code in my original post. It might be helpful to someone else. – Abhishek Jain Jun 24 '10 at 15:13
1

Here is something like that :

public partial class DynamicListViewWindow : Window
{
    public DynamicListViewWindow()
    {
        InitializeComponent();

        ObservableCollection<Person> personList = new ObservableCollection<Person>();

        personList.Add(new Person() { FirstName = "John", LastName = "Doe", Age = 30, Address = "123 Doe Street", Phone = "111-111-1111" });
        personList.Add(new Person() { FirstName = "Jane", LastName = "Doe", Age = 28, Address = "123 Doe Street", Phone = "222-222-2222" });
        personList.Add(new Person() { FirstName = "Mark", LastName = "Doe", Age = 15, Address = "123 Doe Street", Phone = "333-333-3333" });
        personList.Add(new Person() { FirstName = "John", LastName = "Smith", Age = 40, Address = "123 Doe Street", Phone = "444-444-4444" });
        personList.Add(new Person() { FirstName = "Rosy", LastName = "Smith", Age = 36, Address = "123 Doe Street", Phone = "555-555-5555" });

        PersonListView.ItemsSource = personList;
    }

    private void PersonListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (PersonListView.SelectedIndex >= 0)
        {
            Object data = PersonListView.SelectedItem;
            PropertyInfo[] properties = data.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

            ExtraPropertiesPanel.Children.Clear();

            foreach (PropertyInfo prop in properties)
            {
                TextBox tb = new TextBox();
                Binding b = new Binding() { Source = data, Path = new PropertyPath(prop.Name) };
                tb.SetBinding(TextBox.TextProperty, b);
                ExtraPropertiesPanel.Children.Add(tb);
            }
        }
    }
}

public class Person
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public Int32 Age { get; set; }
    public String Address { get; set; }
    public String Phone { get; set; }
}

XAML

<Window x:Class="WPFApplication1.DynamicListViewWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window"
    Height="300"
    Width="300">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Border Grid.Column="0">
        <ListView Name="PersonListView" SelectionChanged="PersonListView_SelectionChanged">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="First Name"
                                    DisplayMemberBinding="{Binding FirstName}" />
                    <GridViewColumn Header="Last Name"
                                    DisplayMemberBinding="{Binding LastName}" />
                </GridView>
            </ListView.View>
        </ListView>
    </Border>
    <Border Grid.Column="1">
        <StackPanel Name="ExtraPropertiesPanel"></StackPanel>
    </Border>
</Grid>

decyclone
  • 30,394
  • 6
  • 63
  • 80