WPF-MVVM Radio Button generated automatically - c#

I have an application where I present a Form. The form contains multiple Radio Buttons and they are displayed 1 next to each other. I need to load the colors from the list and create a radio button for each color, then when the users selects a color I want to grab the "SelectedItem" from the control. I know you can do that easily with a list but how do I do that when I need to place the controls next to each other ??
Code :
<Grid>
<StackPanel VerticalAlignment="Top">
<GroupBox Name="CheckBoxes" Margin="5" >
<StackPanel Name="wrpCheckBoxes" DataContext="{Binding ListParts}">
<RadioButton Name="chkRed" Content="{Binding Description}" Visibility="{Binding DataBindingModel.ColorRed}" Tag="{Binding ID}" />
<RadioButton Name="chkGreen" Content="Green" Visibility="{Binding DataBindingModel.ColorGreen}" />
<RadioButton Name="chkBlue" Content="Blue" Visibility="{Binding DataBindingModel.ColorBlue}" />
<RadioButton Name="chkGray" Content="Gray" Visibility="{Binding DataBindingModel.ColorGray}" />
<RadioButton Name="chkYellow" Content="Yellow" Visibility="{Binding DataBindingModel.ColorYellow}" />
<RadioButton Name="chkBlack" Content="Black" Visibility="{Binding DataBindingModel.ColorBlack}" />
</StackPanel>
</GroupBox>
</StackPanel>
<StackPanel VerticalAlignment="Bottom" Margin="5">
<ListView x:Name="listBoxItems" BorderThickness="1" ItemsSource="{Binding ListParts}">
<ListView.View>
<GridView>
<GridViewColumn Header="Index" DisplayMemberBinding="{Binding Index}" />
<GridViewColumn Header="Description" DisplayMemberBinding="{Binding Description}" />
<GridViewColumn Header="Price" DisplayMemberBinding="{Binding Price}" />
</GridView>
</ListView.View>
</ListView>
<!--<ListBox x:Name="listBoxItems" ItemsSource="{Binding ListParts}">
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton GroupName="rbList" Tag="{Binding}" Content="{Binding Description}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>-->
</StackPanel>
</Grid>
Remark : the ListParts is just a list containing the colors, also this view is attached to a viewModel
ViewModel :
public class DataBindingViewModel : ViewModelBase
{
#region Private Fields
private DataBindingModel _DataBindingModel;
private List<PartsModel> _ListParts;
private string _Description1;
private int _TagID;
#endregion
#region Properties
public DataBindingModel DataBindingModel
{
get { return this._DataBindingModel; }
set
{
if (this._DataBindingModel == value)
return;
this._DataBindingModel = value;
OnPropertyChanged("DataBindingModel");
}
}
public List<PartsModel> ListParts
{
get { return this._ListParts; }
set
{
if (this._ListParts == value)
return;
this._ListParts = value;
OnPropertyChanged("ListParts");
}
}
public string Description1
{
get { return this._Description1; }
set
{
if (this._Description1 == value)
return;
this._Description1 = value;
OnPropertyChanged("Description1");
}
}
public int TagID
{
get { return this._TagID; }
set
{
if (this._TagID == value)
return;
this._TagID = value;
OnPropertyChanged("TagID");
}
}
#endregion
public DataBindingViewModel(DataBindingModel DataBinding)
{
this.DataBindingModel = DataBinding;
this.ListParts = Common.GetData();
}
}
And the Common Class is just laoding the Data :
public static class Common
{
public static List<PartsModel> GetData()
{
List<PartsModel> listParts = new List<PartsModel>();
listParts.Add(new PartsModel(1, "1234561", "Color Red", Convert.ToDecimal(15.99)));
listParts.Add(new PartsModel(2, "1234562", "Color Green", Convert.ToDecimal(17.00)));
listParts.Add(new PartsModel(3, "1234563", "Color Blue", Convert.ToDecimal(12.95)));
listParts.Add(new PartsModel(4, "1234564", "Color Gray", Convert.ToDecimal(9.95)));
listParts.Add(new PartsModel(5, "1234565", "Color Yellow", Convert.ToDecimal(10.55)));
listParts.Add(new PartsModel(6, "1234566", "Color Black", Convert.ToDecimal(99.99)));
return listParts;
}
}
How can I display the members of the ListParts on each of my radio button, without the use of a ListView ?
Let me know if you guys need more info and thanks for the answers

You can use ListBox.ItemsPanel to specify the type of panel you want - probably <StackPanel Orientation="Horizontal/>.
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton GroupName="rbList" Tag="{Binding}" Content="{Binding Description}" />
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"
VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</ItemsPanelTemplate>
<ListBox.ItemsPanel>
<ListBox>
See the examples in the ItemsPanel property documentation on MSDN for more information.

Related

C# WPF - Command Binding of toggle button not working

Good day,
I would like to ask question on how to properly bind the RelayCommand UpdateUserCommand() in toggle button. Please see my code below
<UserControl x:Class="istock.View.UserMasterList"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:local="clr-namespace:istock.View"
mc:Ignorable="d"
MinHeight="450" Width="Auto" MinWidth="1024" FontFamily="Segoe UI LIght">
<Grid>
<Border Padding="30 15">
<StackPanel>
<Grid>
<TextBlock Text="User Management" FontSize="20" HorizontalAlignment="Left" Width="Auto" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Width="Auto">
<Button x:Name="btnNew" Foreground="#FFFF">
<StackPanel Orientation="Horizontal">
<materialDesign:PackIcon Kind="PlusBoxOutline" Margin="0 5" />
<TextBlock Text="New User" Margin="5 3 5 0" />
</StackPanel>
</Button>
</StackPanel>
</Grid>
<ListView ItemsSource="{Binding Path = UserMasterListProp}">
<ListView.View>
<GridView>
<GridViewColumn Header="ID" Width="auto" DisplayMemberBinding="{Binding Path = Id}"></GridViewColumn>
<GridViewColumn Header="Username" Width="120" DisplayMemberBinding="{Binding Path = Username}"></GridViewColumn>
<GridViewColumn Header="Firstname" Width="120" DisplayMemberBinding="{Binding Path = Firstname}"></GridViewColumn>
<GridViewColumn Header="Middlename" Width="120" DisplayMemberBinding="{Binding Path = Middlename}"></GridViewColumn>
<GridViewColumn Header="Lastname" Width="120" DisplayMemberBinding="{Binding Path = Lastname}"></GridViewColumn>
<GridViewColumn Header="Role" Width="100" DisplayMemberBinding="{Binding Path = Role}"></GridViewColumn>
<GridViewColumn Header="Activated">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ToggleButton x:Name="tbtnActivated" Style="{DynamicResource MaterialDesignSwitchToggleButton}" IsChecked="{Binding Path = Activated}" Command="{Binding Path = UserViewModel.UpdateUserCommand}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Locked">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ToggleButton x:Name="tbtnLocked" Style="{DynamicResource MaterialDesignSwitchToggleButton}" IsChecked="{Binding Path = Locked}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</StackPanel>
</Border>
</Grid>
Here is my Command Code which was initialized and CanExecute() method is always true.
public class RelayCommand : ICommand
{
private Action ExecuteCmd;
public RelayCommand(Action paramAction)
{
this.ExecuteCmd = paramAction;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
this.ExecuteCmd();
}
}
And Here's my code in ViewModel which the UpdateUser() method will be fired
by my UpdateUserCommand()
#region Update Command and Method
private RelayCommand updateUserCommand;
public RelayCommand UpdateUserCommand
{
get { return updateUserCommand; }
}
public void UpdateUser()
{
try
{
var isExist = this.userService.ApplyService_FindByIdOrUsername(UserModel.Id, UserModel.Username);
if(isExist == null)
{
var isUpdated = this.userService.ApplyService_Update(UserModel);
if (isUpdated == true)
{
this.Message = "Update sucesss.";
this.Populate_UserMasterList();
}
}
else
{
this.Message = "Update failed. ID or Username already exist.";
return;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
return;
}
}
#endregion
Here is the implementation of the Data Context in Code Behind of the User Control
public partial class UserMasterList : UserControl
{
public UserMasterList()
{
InitializeComponent();
UserViewModel userViewModel = new UserViewModel();
this.DataContext = userViewModel;
}
}
Please help. If ever my code is confusing, I am open for question. Thanks
You could bind to a property of the parent UserControl using a {RelativeSource}:
<ToggleButton x:Name="tbtnActivated"
Style="{DynamicResource MaterialDesignSwitchToggleButton}"
IsChecked="{Binding Activated}"
Command="{Binding DataContext.UpdateUserCommand,
RelativeSource={RelativeSource AncestorType=UserControl}}" />

Datagrid row selected showing error "Sequence contains no matching element"

I have a datagrid which holds the User information. Now once, I click on the selected row, I want to display the user information such as their roles and allow the user to edit the user roles by clicking on the combobox. Under my data template I have the combobox in my xaml. Since using the datatemplate, the combobox name couldnt be found, I am using the following method below to get the children from the grid.
Here is the code to get the children element:
private List<FrameworkElement> GetChildren(DependencyObject parent)
{
List<FrameworkElement> controls = new List<FrameworkElement>();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); ++i)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is FrameworkElement)
{
controls.Add(child as FrameworkElement);
}
controls.AddRange(GetChildren(child));
}
return controls;
}
I created the selection changed event for the datagrid:
private void userDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var userRolesList = new User().getUserRoles();
ComboBox cbUserRole = (ComboBox)GetChildren(userDataGrid).First(x => x.Name == "cbUserRole");
cbUserRole.ItemsSource = userRolesList;
}
Now when I run this code, I am being shown error message
Sequence contains no matching element
The same method I use for my textboxes, I am able to display the values and edit the values too. But for my combobox its not working the way it supposed to. Can someone please help me on this. Thanks.
This is my xaml code:
<DataGrid AutoGenerateColumns="False" Grid.Row="2" Grid.ColumnSpan="4" Grid.RowSpan="3" x:Name="userDataGrid" Margin="70,0.2,70,0" ItemsSource="{Binding}" SelectionChanged="userDataGrid_SelectionChanged">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding UserId}"/>
<DataGridTextColumn Header="Username" Binding="{Binding UserName}"/>
<DataGridTextColumn Header="Email" Binding="{Binding UserEmail}"/>
<DataGridTextColumn Header="User Role" Binding="{Binding UserRole}"/>
<DataGridTextColumn Header="Created Date" Binding="{Binding UserCreatedDate}"/>
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<Border BorderThickness="0" Background="BlanchedAlmond" Padding="10">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="12" Text="User ID: " VerticalAlignment="Center" />
<TextBlock x:Name="txtBlockId" FontSize="16" Foreground="MidnightBlue" Text="{Binding UserId, Mode=TwoWay}" VerticalAlignment="Center" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="12" Text="First Name: " VerticalAlignment="Center" />
<TextBox x:Name="txtFirstName" FontSize="16" Foreground="MidnightBlue" Text="{Binding UserFirstName, Mode=TwoWay}" VerticalAlignment="Center" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="12" Text="Last Name: " VerticalAlignment="Center" />
<TextBox x:Name="txtLastName" FontSize="16" Foreground="MidnightBlue" Text="{Binding UserLastName}" VerticalAlignment="Center" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="12" Text="User Role: " VerticalAlignment="Center" />
<ComboBox x:Name="cbUserRole" FlowDirection="LeftToRight" FontSize="16" Foreground="MidnightBlue" HorizontalAlignment="Stretch" VerticalAlignment="Center" SelectionChanged="cbUserRole_Click"/>
</StackPanel>
<StackPanel>
<Button x:Name="btnUpdate" Content="Update" VerticalAlignment="Center" HorizontalAlignment="Right" Click="btnUpdate_Click"/>
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
Thanks
I've been seeing you asking around how to work with this, let me show you one way, hope this helps, but I recommend you read about MVVM patterns and frameworks like MVVMLight for WPF.
Well, for this, first you need to install Install-Package MvvmLight -Version 5.4.1
Then you may need to fix one reference issue, in the ViewModelLocator, remove all the usings and replace with:
using GalaSoft.MvvmLight.Ioc;
using CommonServiceLocator;
Now, your MainWindowView.xaml, it should like:
<Window x:Class="WpfApp2.MainWindow"
x:Name="root"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:WpfApp2.ViewModel"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<vm:MainViewModel x:Name="Model"/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<DataGrid AutoGenerateColumns="False" x:Name="userDataGrid" Margin="70,0.2,70,0" ItemsSource="{Binding Users}">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding UserId}"/>
<DataGridTextColumn Header="Username" Binding="{Binding UserName}"/>
<DataGridTextColumn Header="Email" Binding="{Binding UserEmail}"/>
<DataGridTextColumn Header="User Role" Binding="{Binding UserRole}"/>
<DataGridTextColumn Header="Created Date" Binding="{Binding UserCreatedDate}"/>
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<Border BorderThickness="0" Background="BlanchedAlmond" Padding="10">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="12" Text="User ID: " VerticalAlignment="Center" />
<TextBlock x:Name="txtBlockId" FontSize="16" Foreground="MidnightBlue" Text="{Binding UserId, Mode=TwoWay}" VerticalAlignment="Center" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="12" Text="First Name: " VerticalAlignment="Center" />
<TextBox x:Name="txtFirstName" FontSize="16" Foreground="MidnightBlue" Text="{Binding UserFirstName, Mode=TwoWay}" VerticalAlignment="Center" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="12" Text="Last Name: " VerticalAlignment="Center" />
<TextBox x:Name="txtLastName" FontSize="16" Foreground="MidnightBlue" Text="{Binding UserLastName}" VerticalAlignment="Center" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="12" Text="User Role: " VerticalAlignment="Center" />
<ComboBox ItemsSource="{Binding Path=DataContext.UserRoles, ElementName=root}" SelectionChanged='CbUserRole_OnSelectionChanged' SelectedItem="{Binding UserRole}" x:Name="cbUserRole" FlowDirection="LeftToRight" FontSize="16" Foreground="MidnightBlue" HorizontalAlignment="Stretch" VerticalAlignment="Center" />
</StackPanel>
<StackPanel>
<Button x:Name="btnUpdate" Content="Update" VerticalAlignment="Center" HorizontalAlignment="Right" Command="{Binding UpdateCommand, ElementName=Model}" CommandParameter="{Binding}" />
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
</Grid>
</Window>
Then in your code-behind, there's a little event handling that needs to be done, when changing the roles,
using System.Windows;
using System.Windows.Controls;
using WpfApp2.ViewModel;
namespace WpfApp2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public MainViewModel ViewModel => (MainViewModel) DataContext;
private void CbUserRole_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox cb = (ComboBox)sender;
if (cb != null)
{
ViewModel.SelectedUserRole = (UserRole)cb.SelectedItem;
}
}
}
}
Then you should create a ViewModel like so (ViewModel -> MainViewModel.cs):
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using GalaSoft.MvvmLight.Command;
using WpfApp2.Data;
namespace WpfApp2.ViewModel
{
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
PopulateUserTestData();
UpdateCommand = new RelayCommand<User>(UpdateUser);
}
private ObservableCollection<User> _users;
public ObservableCollection<User> Users
{
get => _users;
set
{
if (_users != value)
{
_users = value;
NotifyPropertyChanged();
}
}
}
private UserRole _userRole;
public UserRole SelectedUserRole
{
get => _userRole;
set
{
if (_userRole != value)
{
_userRole = value;
NotifyPropertyChanged();
}
}
}
public RelayCommand<User> UpdateCommand { get; }
public IEnumerable<UserRole> UserRoles => Enum.GetValues(typeof(UserRole)).Cast<UserRole>();
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private void UpdateUser(User user)
{
Users.Single(u => u.UserId == user.UserId).UserRole = SelectedUserRole;
// Do updates on your context (or in-memory).
PrintUsersOnDebug();
}
#region Test data and diagnostics support
private void PrintUsersOnDebug()
{
foreach (User user in Users)
{
Debug.WriteLine("Username: " + user.UserName + " Role: " + user.UserRole);
}
}
private void PopulateUserTestData()
{
Users = new ObservableCollection<User>
{
new User
{
UserId = 1,
UserCreatedDate = DateTime.Now,
UserEmail = "johndoe1#email.com",
UserFirstName = "John",
UserLastName = "Doe",
UserName = "johnd",
UserRole = UserRole.Administrator
},
new User
{
UserId = 2,
UserCreatedDate = DateTime.Now,
UserEmail = "billgordon#email.com",
UserFirstName = "Bill",
UserLastName = "Gordon",
UserName = "billg",
UserRole = UserRole.SuperUser
}
};
PrintUsersOnDebug();
}
#endregion
}
}
Other related classes:
Data->User.cs
using System;
namespace WpfApp2.Data
{
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
public string UserEmail { get; set; }
public UserRole UserRole { get; set; }
public DateTime UserCreatedDate { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
}
}
UserRole.cs
namespace WpfApp2
{
public enum UserRole
{
Administrator,
User,
SuperUser
}
}
Now since I just designed this test app to view the changing data in this case roles, I designed this to be just viewable on output window. As you change the roles and click the update button, inspect the output window.
If you simply want to populate the ComboBox in the RowDetailsTemplate, you could handle its Loaded event:
private void cbUserRole_Loaded(object sender, RoutedEventArgs e)
{
ComboBox cbUserRole = (ComboBox)sender;
if (cbUserRole.ItemsSource == null)
cbUserRole.ItemsSource = new User().getUserRoles();
}
XAML:
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="12" Text="User Role: " VerticalAlignment="Center" />
<ComboBox x:Name="cbUserRole"
Loaded="cbUserRole_Loaded"
FlowDirection="LeftToRight" FontSize="16" Foreground="MidnightBlue" HorizontalAlignment="Stretch"
VerticalAlignment="Center"
SelectionChanged="cbUserRole_Click"/>
</StackPanel>

Changing TextBox's Text in a ListView does not update ObservableCollection<string> Source

I have a quite complicated structure of ListViews. Inside this structure are TextBoxes with values from my ViewModel. When I change a value in some textbox, the property in ViewModel doesn't update. The "AllTexts" property in ViewModel still contains only "Hello" strings.
Basically, I want to show user structure of strings and then let the user change this structure. After he finishes his modification I want to save his changes. "Hello" strings are here just for testing.
My ViewModel:
class MainWindowViewModel
{
public ObservableCollection<ObservableCollection<ObservableCollection<string>>> AllTexts { get; set; }
public int SelectedGroupIndex { get; set; }
public int SelectedColumnIndex { get; set; }
public ICommand AddGroup { get; private set; }
public ICommand AddColumn { get; private set; }
public MainWindowViewModel()
{
this.AllTexts = new ObservableCollection<ObservableCollection<ObservableCollection<string>>>();
this.SelectedGroupIndex = -1;
this.SelectedColumnIndex = -1;
this.AddGroup = new Command(this.AddGroupCommandHandler);
this.AddColumn = new Command(this.AddColumnCommandHandler);
}
private void AddGroupCommandHandler()
{
var tempColumn = new ObservableCollection<string>() { "Hello", "Hello", "Hello", "Hello", "Hello" };
var tempGroup = new ObservableCollection<ObservableCollection<string>>();
tempGroup.Add(tempColumn);
this.AllTexts.Add(new ObservableCollection<ObservableCollection<string>>(tempGroup));
}
private void AddColumnCommandHandler()
{
if (this.SelectedGroupIndex >= 0 && this.SelectedGroupIndex < this.AllTexts.Count)
{
var tempColumn = new ObservableCollection<string>() { "Hello", "Hello", "Hello", "Hello", "Hello" };
this.AllTexts[this.SelectedGroupIndex].Add(tempColumn);
}
}
}
My View:
<Window.Resources>
<ResourceDictionary>
<local:MainWindowViewModel x:Key="vm" />
</ResourceDictionary>
</Window.Resources>
<Grid Margin="10,10,10,10" VerticalAlignment="Top">
<Grid.RowDefinitions>
<RowDefinition Height="300" />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<ListView Grid.Row="0"
ItemsSource="{Binding AllTexts, Source={StaticResource vm}, Mode=TwoWay}"
Background="Red"
SelectedIndex="{Binding SelectedGroupIndex, Source={StaticResource vm}}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<ListView
Background="Yellow"
ItemsSource="{Binding Path=., Mode=TwoWay}"
SelectedIndex="{Binding SelectedColumnIndex, Source={StaticResource vm}}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<ListView
Background="Green"
ItemsSource="{Binding Path=., Mode=TwoWay}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=., Mode=TwoWay, NotifyOnSourceUpdated=True}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Width="100" Height="40"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackPanel Grid.Row="1" Orientation="Horizontal" Margin="0,20,0,0">
<Button Content="Add Group" Width="120" Height="30"
Command="{Binding AddGroup, Source={StaticResource vm}}" />
<Button Content="Add Column" Margin="20,0,0,0" Width="120" Height="30"
Command="{Binding AddColumn, Source={StaticResource vm}}" />
</StackPanel>
<StackPanel Grid.Row="2" Orientation="Horizontal" Margin="0,20,0,0">
<TextBlock Width="120" Height="30" FontSize="20"
Text="{Binding SelectedGroupIndex, Source={StaticResource vm}}" />
<TextBlock Width="120" Height="30" Margin="20,0,0,0" FontSize="20"
Text="{Binding SelectedColumnIndex, Source={StaticResource vm}}" />
</StackPanel>
</Grid>
Could someone, please help me?
Thank you.
Your ViewModel has to notify the View about the changes, or else the View retains original values of the ViewModel
In this case, string cannot notify the changes made to itself. Only its enclosing observable collection can notify about changes made to itself like add or remove and does not monitor further into its elements.
So you need an observable string:
public class MyString : DependencyObject
{
public string Value
{
get { return (string)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(string), typeof(MyString), new PropertyMetadata(""));
}
To use in the collection:
public ObservableCollection<ObservableCollection<ObservableCollection<MyString>>> AllTexts { get; set; }
I also added the following line to the MyString class in order to test the code and it worked.
public static MyString Hello { get { return new MyString { Value = "Hello" }; } }
Obviously, this is how it will be used:
var tempColumn = new ObservableCollection<MyString>() { MyString.Hello, MyString.Hello, MyString.Hello, MyString.Hello, MyString.Hello };
In xaml there are also some unnecessary things which you can get rid of:
use ItemsSource="{Binding}" for both ListViews, and use Text="{Binding Value}" for the TextBox. (there is no need for explicit TwoWay in any of those)

wpf binding to selectedItem

In my example I'm binding to a selectedItem from a ListBox. I was wondering how can i set the binding in the stack panel so i don't have to then individually bind to each control.
Can I just bind the stack panel and then the sub controls just get bound like so (pseudo code)
<StackPanel Grid.Column="2" Content="{Binding SelectedItem.Name, ElementName=ItemList}"/>
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Text="{Binding Kids, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>
Code
<ListBox Grid.Column="0"
x:Name="ItemList"
Background="AliceBlue"
ItemsSource="{Binding VNodes}"
SelectedItem="{Binding SelectedVNode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<ListBox.ItemTemplate>
<DataTemplate>
<WrapPanel>
<TextBlock Text="Name: " />
<TextBlock Text="{Binding Name}" FontWeight="Bold" />
</WrapPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<GridSplitter Grid.Column="1" Width="5" HorizontalAlignment="Stretch" />
<StackPanel Grid.Column="2">
<TextBox Text="{Binding SelectedItem.Name, ElementName=ItemList, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Text="{Binding SelectedItem.Kids, ElementName=ItemList, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Text="{Binding SelectedItem.Age, ElementName=ItemList, UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>
In WPF, every Item has a DataContext for Bindings, You can set the DataContext of Stackpanel to
{Binding ElementName=ItemList, Path=SelectedItem},
And simply put
<TextBox Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}"/>
inside the StackPanel as You wanted ;)
We have this class:
public class Jobs
{
public string Name { get; set; }
public List<string> Titles { get; set; }
}
MainViewModel (u need to make 2 property (fill these props random values)):
public MainViewModel()
{
ListJobs = new List<Jobs>();
ListJobs.Add(new Jobs() { Name = "Job1", Titles = new List<string>() {"Job1Title1","Job1Title2","Job1Title3" } });
ListJobs.Add(new Jobs() { Name = "Job2", Titles = new List<string>() {"Job2Title1","Job2Title2","Job2Title3" } });
ListJobs.Add(new Jobs() { Name = "Job3", Titles = new List<string>() {"Job3Title1","Job3Title2","Job3Title3" } });
}
private List<Jobs> listJobs;
public List<Jobs> ListJobs
{
get { return listJobs; }
set
{
if (value != listJobs)
{
listJobs = value;
OnPropertyChanged(nameof(ListJobs));
}
}
}
private Jobs selectedJob;
public Jobs SelectedJob
{
get { return selectedJob; }
set
{
if (value != selectedJob)
{
selectedJob = value;
OnPropertyChanged(nameof(SelectedJob));
}
}
}
XAML:
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<DataGrid x:Name="Jobs" Grid.Column="0" AutoGenerateColumns="False" SelectedItem="{Binding SelectedJob, UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding ListJobs, UpdateSourceTrigger=PropertyChanged}">
<DataGrid.Columns >
<DataGridTextColumn Binding="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}" Header="Job" Width="200*" IsReadOnly="False"/>
</DataGrid.Columns>
</DataGrid>
<DataGrid x:Name="JobTitles" Grid.Column="1" AutoGenerateColumns="False" ItemsSource="{Binding SelectedJob.Titles, UpdateSourceTrigger=PropertyChanged}">
<DataGrid.Columns >
<DataGridTextColumn Header="JobTitle" Width="200*" IsReadOnly="False" Binding="{Binding}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>

Multi selection in WPF Listview and multiple styles

I have an application in WPF (MVVM).
I've created a view model which points to an ObservableCollections to be shown in the ListView.
The ListView has two custom view resources. 'GridView' and a 'TileView' and buttons to switch between them.
When I select multiple items and change to the other view the selected items are not sync...
after trying to debug I think that, for some reason, when changing views it:
Gets the IsSelected value for every Item in the list (That's OK)
Sets (again..) the Items that have just been set (in the other view..) (?)
The markup:
<Window.Resources>
<local:TileView x:Key="ImageView">
<local:TileView.ItemTemplate >
<DataTemplate >
<StackPanel Width="150" VerticalAlignment="Top">
<Image Source="{Binding Path=ImagePath}"/>
<TextBlock TextWrapping="Wrap" HorizontalAlignment="Center" Text="{Binding Path=PhotoReferenceCode}"/>
</StackPanel>
</DataTemplate>
</local:TileView.ItemTemplate>
</local:TileView>
<GridView x:Key ="ListView">
<GridViewColumn Header="Select" Width="100" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid Width="100">
<!--<CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay}" HorizontalAlignment="Center"/>-->
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Image" Width="100" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Path=ImagePath}" Stretch="UniformToFill" HorizontalAlignment="Center" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Reference Code" Width="100" DisplayMemberBinding="{Binding Path=PhotoReferenceCode}"/>
</GridView>
</Window.Resources>
<Grid>
<ListView Margin="0,36,0,0" View="{Binding Path=ViewType, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" SelectionMode="Multiple"
ItemsSource="{Binding Path=InfoList, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}">
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
<Button Name="btnListView" Content="ListView" Click="btnListView_Click" HorizontalAlignment="Left" Margin="10,9,0,0" VerticalAlignment="Top" Width="75"/>
<Button Name="btnImageView" Content="ImageView" Click="btnImageView_Click" HorizontalAlignment="Left" Margin="99,9,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
The Item class:
public class ItemData : INotifyPropertyChanged
{
#region Members
private bool _IsSelected;
public string ImagePath { get; set; }
public string PhotoReferenceCode { get; set; }
#endregion
#region Constractors
public ItemData()
{
}
public ItemData(bool Is_Sected, string Image_Path, int Item_Carat, string Photo_Reference_Code)
{
IsSelected = Is_Sected;
ImagePath = Image_Path;
ItemCarat = Item_Carat;
PhotoReferenceCode = Photo_Reference_Code;
}
#endregion
#region Public
public bool IsSelected
{
get { return _IsSelected; }
set
{
if (this.PropertyChanged != null && _IsSelected != value)
{
_IsSelected = value; OnPropertyChanged("IsSelected");
}
}
}
#endregion
#region Events
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
Any help would be appreciated.
Bind all of the listview's SelectedItems to a property in the view model using TwoWay bind. So the viewModel keeps the selectedItems of the listview and so when the view is changed, the new listview style can pick up the selectedItems from the viewModel

Categories