I should load images to listbox.I have a trouble when I choose images, to listbox added only border without nothing and only one, I have debuged my code and in collection 6 bitmap images, but loaded only 1 border.
1.That is my class Album:
public class Album : INotifyPropertyChanged
{
private string name;
public string Name
{
get { return name; }
set
{
name = value;
OnPropertyChanged(new PropertyChangedEventArgs("Name"));
}
}
private string description;
public string Description
{
get
{
return description;
}
set
{
description = value;
OnPropertyChanged(new PropertyChangedEventArgs("Description"));
}
}
private List<BitmapImage> images;
public List<BitmapImage> Images
{
get
{
return images;
}
set
{
images = value;
OnPropertyChanged(new PropertyChangedEventArgs("Images"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(this, e);
}
public Album() { }
public Album(string name, string description, List<BitmapImage> files)
{
Name = name;
Description = description;
Images = files;
}
}
2.That my code for child window.When i push button create, I write name, description, and add some photos(please check my method for add is it correct).
public partial class DialogCreate : ChildWindow
{
private List<BitmapImage> temps = new List<BitmapImage>();
private string tempName;
private string tempDescription;
public List<BitmapImage> Temps
{
get { return temps; }
set { temps = value; }
}
public string TempName
{
get { return tempName; }
set { tempName = value; }
}
public string TempDescription
{
get { return tempDescription; }
set { tempDescription = value; }
}
private OpenFileDialog addPhoto;
public DialogCreate()
{
InitializeComponent();
addPhoto = new OpenFileDialog();
addPhoto.Multiselect = true;
addPhoto.Filter = "Image files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*";
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
tempName = txtGetName.Text;
tempDescription = txtGetDescription.Text;
this.DialogResult = true;
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
bool result = (bool)addPhoto.ShowDialog();
if (!result)
return;
IEnumerable<FileInfo> file = addPhoto.Files;
foreach (FileInfo files in file)
{
Stream s = files.OpenRead();
BitmapImage i = new BitmapImage();
i.SetSource(s);
temps.Add(i);
}
}
}
3.After that I return to:
private void CreateButton_Click(object sender, RoutedEventArgs e)
{
dialogAlbum = new DialogCreate();
dialogAlbum.Show();
dialogAlbum.Closed += delegate
{
albums.Add(new Album(dialogAlbum.TempName, dialogAlbum.TempDescription, dialogAlbum.Temps));
AlbumScroll.ItemsSource = albums;
lsPhoto.ItemsSource = albums;
};
}
4.That my xaml:
<ListBox Style="{StaticResource ListBoxStyle}" ItemsSource="{Binding Images}" Margin="121,38,171,23" x:Name="lsPhoto" Grid.Column="1" Grid.Row="2" Height="144" Width="600">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border Width="100" Height="100">
<Image x:Name="listPhotos" Source="{Binding}" Width="Auto" Height="Auto"/>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Please help me, what I did wrong?Or give your advertise.
I created a new class something like this
public class ImageInformation:INotifyPropertyChanged
{
public string Name { get; set; }
public BitmapImage ImageInfo { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(this, e);
}
}
I replaced all the places where you use BitmapImage and in mainpage.xaml
<ListBox x:Name="lsPhoto" Grid.RowSpan="2">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Height="25" Width="25">
<Image Height="25" Width="25" Source="{Binding ImageInfo}"></Image>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
With these two changes and other impacted changes, my Listbox shows the image that was selected by the user. If you need the solution i tried, send me a mail.
Related
Please find the below code.
public enum SortByType
{
[Display(Name = "Y Value")]
Y_Value,
[Display(Name = "X Value")]
X_Value,
[Display(Name = "Z Value")]
Z_Value,
}
public class ViewModel : INotifyPropertyChanged
{
ObservableCollection<SortByType> sortList;
SortByType selectedType;
public ViewModel()
{
SortList = new ObservableCollection<SortByType>(Enum.GetValues(typeof(SortByType)).OfType<SortByType>().ToList());
}
public ObservableCollection<SortByType> SortList
{
get
{
return sortList;
}
set
{
sortList = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SortList)));
}
}
public SortByType SelectedType
{
get
{
return selectedType;
}
set
{
selectedType = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedType)));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public partial class MainWindow : Window
{
public MainWindow()
{
DataContext = new ViewModel();
(DataContext as ViewModel).SelectedType = SortByType.Y_Value;
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
(DataContext as ViewModel).SortList.Clear();
(DataContext as ViewModel).SortList = new ObservableCollection<SortByType>(Enum.GetValues(typeof(SortByType)).OfType<SortByType>().ToList());
}
}
<Grid>
<StackPanel VerticalAlignment="Center">
<ComboBox ItemsSource="{Binding SortList}"
SelectedItem="{Binding SelectedType}">
<ComboBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Button Height="25" Width="150" Content="Details" Click="Button_Click"/>
</StackPanel>
</Grid>
Just, Clear the collection and re-initialize the combo box item source on button click event. On this time I have noticed that the Data error shown on the combo box. Can anyone explain what is the exact problem whether it may be a memory issue or some thing i have missed while implement the Item Template
The value of SelectedType must be present in the source collection. It's not when you assign the source property to a new list of new values, unless you set explicitly set it to any of these new values:
private void Button_Click(object sender, RoutedEventArgs e)
{
var viewModel = DataContext as Win32ViewModel;
viewModel.SortList = new ObservableCollection<SortByType>(Enum.GetValues(typeof(SortByType)).OfType<SortByType>().ToList());
viewModel.SelectedType = viewModel.SortList.FirstOrDefault(x => x == viewModel.SelectedType);
}
I have a simple ListBox and a TextBox as under.I want to display the selectedvalue property of Listbox in the textbox,but my ViewModel's selected object is always null.
What am i missing here?
My XAML
<StackPanel>
<Canvas>
<TextBox x:Name="TxtMail" Width="244" FontSize="14" Canvas.Left="36" Canvas.Top="34" Height="20" Text="{Binding CurrentRec.Name,Mode=OneWay}" />
<ListBox x:Name="AllMatching" Width="{Binding ElementName=TxtMail,Path=Width}" Height="100" Canvas.Top="54" Canvas.Left="36" DisplayMemberPath="Name" SelectedItem="{Binding CurrentRec,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedValue="Name" SelectedValuePath="Name" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Auto" />
<Button Content="Test" x:Name="cmdtest" Click="cmdtest_Click"/>
</Canvas>
My ViewModel:
public class VM_Data : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public int p_ID;
public double p_SP, p_CP;
public string p_Name;
public List<DM_Data> AllData;
public DM_Data CurrentRec;
public VM_Data()
{
LoadData();
}
public int ID
{
get { return p_ID; }
set
{
if (p_ID != value)
{
RaisePropertyChangedEvent("ID");
p_ID = value;
}
}
}
public double SP
{
get { return p_SP; }
set
{
if (p_SP != value)
{
RaisePropertyChangedEvent("SP");
p_SP = value;
}
}
}
public double CP
{
get { return p_CP; }
set
{
if (p_CP != value)
{
RaisePropertyChangedEvent("CP");
p_CP = value;
}
}
}
public string Name
{
get { return p_Name; }
set
{
if (p_Name != value)
{
RaisePropertyChangedEvent("Name");
p_Name = value;
}
}
}
private void LoadData()
{
AllData = new List<DM_Data>();
string[] strNames = "Jatinder;Shashvat;shashikala;shamsher;shahid;justin;jatin;jolly;ajay;ahan;vijay;suresh;namita;nisha;negar;zenith;zan;zen;zutshi;harish;hercules;harman;ramesh;shashank;mandeep;aman;amandeep;amarjit;asim;akshay;amol;ritesh;ritivik;riz;samana;samaira;bhagwandass;bhagwan;bhawna;bhavna".Split(';');
for(int i=0;i<=strNames.GetUpperBound(0);i++)
{
DM_Data NewRec = new DM_Data();
NewRec.CP = new Random().Next(200, 400);
NewRec.SP = new Random().Next(1, 10);
NewRec.ID = i + 1;
NewRec.Name = strNames[i];
AllData.Add(NewRec);
}
AllData = AllData.OrderBy(item => item.Name).ToList();
}
private void RaisePropertyChangedEvent(string Property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(Property));
}
}
}
My DataModel
public class DM_Data
{
public int p_ID;
public double p_SP, p_CP;
public string p_Name;
public int ID
{
get { return p_ID; }
set { p_ID = value; }
}
public double SP
{
get { return p_SP; }
set { p_SP = value; }
}
public double CP
{
get { return p_CP; }
set { p_CP = value; }
}
public string Name
{
get { return p_Name; }
set { p_Name = value; }
}
MainWindow.Xaml.cs
public partial class MainWindow : Window
{
VM_Data ViewModel;
public MainWindow()
{
InitializeComponent();
ViewModel = new VM_Data();
this.DataContext = ViewModel;
AllMatching.ItemsSource = ViewModel.AllData;
}
private void cmdtest_Click(object sender, RoutedEventArgs e)
{
DM_Data crec = ViewModel.CurrentRec;
}
}
CurrentRec must be a property that raises the PropertyChanged event:
private DM_Data _currentRec;
public DM_Data CurrentRec
{
get { return _currentRec; }
set { _currentRec = value; RaisePropertyChangedEvent("CurrentRec"); }
}
In the code you have posted, it is a field and you cannot bind to fields:
public DM_Data CurrentRec;
You can't bind to fields! CurrentRec must be a property. At now it is a field.
Why do you set ItemsSource in code-behind? Set it in XAML.
You should call RaisePropertyChangedEvent after you've changed backing field, not before.
It is not right pattern for events raising: if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(Property)); } You need to save event delegate to variable first or use ?.Invoke.
Don't create new instances of Random on every iteration of loop because you will get equal values. Create the only one outside of the loop and use it.
What you are doing is kind of MVVM, but not really.
Here is a quick fix anyway:
Please take a look at the Bindings.
<StackPanel>
<Canvas>
<TextBox x:Name="TxtMail" Width="244" FontSize="14" Canvas.Left="36" Canvas.Top="34" Height="20" Text="{Binding ElementName=AllMatching, Path=SelectedItem.Name}" />
<ListBox x:Name="AllMatching"
Width="{Binding ElementName=TxtMail,Path=Width}"
Height="100"
Canvas.Top="54"
Canvas.Left="36"
DisplayMemberPath="Name"
SelectedItem="{Binding CurrentRec,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.HorizontalScrollBarVisibility="Auto" />
<Button Content="Test" x:Name="cmdtest" Click="cmdtest_Click"/>
</Canvas>
</StackPanel>
I think you get the idea at: Text="{Binding ElementName=AllMatching, Path=SelectedItem.Name}".
Aditional Information
First:
You fire to early dude. Please first assign the value and then say its changed.
if (p_Name != value)
{
RaisePropertyChangedEvent("Name");
p_Name = value;
}
Second:
Use a ObservableCollection<DM_Data> to let your ListBox know about changes.
Third:
Use the posibility of Binding
Remove AllMatching.ItemsSource = ViewModel.AllData; and go like
<ListBox x:Name="AllMatching"
ItemsSource="{Binding Path=AllData}"
...
/>
And after all of this - please man check out some tutorials. And also refactor your code from VM_Data to DataViewModel thank you sir.
I want to pass selected items of listview checkbox in view model, later I will use further process to store in database.
Code in the FormWeek.xaml as
<Window.DataContext>
<Binding Source="{StaticResource Locator}" Path="TaskExecDefModel"></Binding>
</Window.DataContext>
<Window.Resources>
<ResourceDictionary>
<DataTemplate x:Key="ItemDataTemplate">
<CheckBox
x:Name="checkbox"
Content="{Binding}" Command="{Binding CheckBoxCommand}" CommandParameter="{Binding ElementName=checkedListView, Path=SelectedItems}"
IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}, Path=IsSelected}" />
</DataTemplate>
</ResourceDictionary>
<StackPanel Grid.Column="1" Grid.Row="3" Margin="5">
<CheckBox x:Name="selectAll" Content="Select all" Click="OnSelectAllChanged"/>
<ListView x:Name="checkedListView" SelectionMode="Multiple" ItemsSource="{Binding CollectionOfDays}" DataContext="{Binding}"
ItemTemplate="{StaticResource ItemDataTemplate}" SelectedValue="WorkingDay"
CheckBox.Unchecked="OnUncheckItem" SelectionChanged="SelectDays" SelectedItem="{Binding SelectedItems}">
</ListView>
</StackPanel>
Code in FormWeek.xaml.cs
private void SelectDays(object sender, SelectionChangedEventArgs e)
{
(this.DataContext as TaskExecDefinitionViewModel).OnCheckBoxCommand(checkedListView.SelectedItems,true);
}
My View Model TaskWeek.cs as follows
//Declaration
private RelayCommand<object> _checkBoxCommand;
public ObservableCollection<string> CollectionOfDays { get; set; }
public ObservableCollection<string> SelectedItems { get; set; }
public RelayCommand<object> CheckBoxCommand
{
get
{
if (_checkBoxCommand == null)
{
_checkBoxCommand = new RelayCommand<object>((args) => OnCheckBoxCommand(args,true));
// _checkBoxCommand = new RelayCommand(() => OnCheckBoxCommand(object args));
}
return _checkBoxCommand;
}
}
//Constructor
CollectionOfDays = new ObservableCollection<string>();
//Method
private void GetWeekDays()
{
try
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
CollectionOfDays.Add("Saturday");
CollectionOfDays.Add("Sunday");
CollectionOfDays.Add("Monday");
CollectionOfDays.Add("Tuesday");
CollectionOfDays.Add("Wednesday");
CollectionOfDays.Add("Thursday");
CollectionOfDays.Add("Friday");
}));
}
catch(Exception Ex)
{
MessageBox.Show(Ex.Message, "TaskWeek:GetWeekDays");
}
}
public void OnCheckBoxCommand(object obj, bool _direction)
{
try
{
if (SelectedItems == null)
SelectedItems = new ObservableCollection<string>();
if (obj != null)
{
SelectedItems.Clear();
StringBuilder items = new StringBuilder();
if (_direction)
{
foreach (string item in CollectionOfDays)
{
items.AppendFormat(item + ",");
}
}
MessageBox.Show(items.ToString());
}
else
SelectedItems.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "TaskDefinition:OnCheckBoxCommand");
}
}
And below is button click commond to save the data.
<Button Grid.Column="2" Grid.Row="2" Content="Save" HorizontalAlignment="Center" VerticalAlignment="Bottom"
Command="{Binding InsertExecDefCommand}" Margin="5" >
Now my requirement is to pass selected listview items to view model through command object. I had done this using following code in FormWeek.xam.cs through SelectionChanged event as
private void OnSelectedItems(object sender, RoutedEventArgs e)
{
StringBuilder items = new StringBuilder();
foreach (string item in checkedListView.SelectedItems)
{
items.AppendFormat(item + ",");
}
string AllDays= items.ToString();
}
But please let me know how to achieve this logic through MVVM. How to get selecteditems in my view model TaskWeek.cs
After R&D and google i had done chages through RelayCommand. In OnCheckBoxCommand method foreach statement is wrong it is passing all days. I want to pass only selected listview item. Please suggest me what is wrong in OnCheckBoxCommand method.
Here are my findings;
use this code in code behind of FormWeek.xaml:
private void SelectDays(object sender, SelectionChangedEventArgs e)
{
(this.DataContext as TaskExecDefinitionViewModel).OnCheckBoxCommand(checkedListView.SelectedItems,true);
}
And in 'OnCheckBoxCommand': -
public void OnCheckBoxCommand(object obj, bool _direction)
{
try
{
if (SelectedItems == null) SelectedItems = new ObservableCollection<string>();
if (obj != null)
{
SelectedItems.Clear();
var _list = ((IList)obj).Cast<string>().ToList();
if (_direction)
{
_list.ForEach(item => SelectedItems.Add(item));
}
}
else
SelectedItems.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "TaskDefinition:OnCheckBoxCommand");
}
}
Have a nice day man.....keep going.
Hi try something like this
<StackPanel Grid.Column="1" Grid.Row="3" Margin="5">
<CheckBox x:Name="selectAll" Content="Select all" Command="{Binding CheckBoxCommand}" CommandParameter="{Binding IsChecked, RelativeSource={RelativeSource Mode=Self}}"/>
<ListView x:Name="checkedListView" SelectionMode="Extended" ItemsSource="{Binding CollectionOfDays}" SelectedItem="{Binding SelectedItems}"/>
</StackPanel>
public class MainViewModel
{
public MainViewModel()
{
CollectionOfDays = new ObservableCollection<string>();
SelectedItems = new ObservableCollection<string>();
CollectionOfDays.Add("Saturday");
CollectionOfDays.Add("Sunday");
CollectionOfDays.Add("Monday");
CollectionOfDays.Add("Tuesday");
CollectionOfDays.Add("Wednesday");
CollectionOfDays.Add("Thursday");
CollectionOfDays.Add("Friday");
}
private CommandHandler _checkBoxCommand;
public CommandHandler CheckBoxCommand
{
get
{
return _checkBoxCommand ?? (_checkBoxCommand=new CommandHandler((param)=>OnCheckBoxCommand(param)));
}
}
public ObservableCollection<string> CollectionOfDays { get; set; }
public ObservableCollection<string> SelectedItems {get;set;}
private void OnCheckBoxCommand(object obj)
{
if (obj is bool)
{
if (SelectedItems == null)
SelectedItems = new ObservableCollection<string>();
if ((bool)obj)
{
SelectedItems.Clear();
foreach (var item in CollectionOfDays)
{
SelectedItems.Add(item);
}
}
else
SelectedItems.Clear();
}
}
}
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
I hope this will give you an idea.
Hello I have problem with binding data to Listbox. In shortway... I want list all my Skydrive files.
My XAML
<TextBlock Height="35" HorizontalAlignment="Left" Margin="9,6,0,0" Name="infoTextBlock" Text="" VerticalAlignment="Top" Width="Auto" />
<my:SignInButton Name="signInButton1" ClientId="<correct ClientId>" Scopes="wl.signin wl.basic wl.skydrive" Branding="Windows" TextType="SignIn" SessionChanged="signInButton1_SessionChanged" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="198,-6,0,0" />
<StackPanel Height="578" HorizontalAlignment="Left" Margin="10,50,0,0" Name="StackContentPanel" VerticalAlignment="Top" Width="440">
<ListBox Height="465" Name="FileList" Width="380" ItemsSource="{Binding Files}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
My class and cs.
namespace EReader.ViewModel
{
public class File
{
public File()
{}
private string name;
public string Name
{
get { return this.name; }
set { this.name = value; }
}
}
}
public class FilesManager
{
public ObservableCollection<string> Files;
public FilesManager()
{
Files = new ObservableCollection<string>();
}
}
namespace EReader
{
public partial class MainPage : PhoneApplicationPage
{
private LiveConnectClient client;
// Constructor
public MainPage()
{
InitializeComponent();
}
private void signInButton1_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(e.Session);
infoTextBlock.Text = "Signed in.";
client.GetCompleted +=
new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.GetAsync("/me/skydrive/files/");
}
else
{
infoTextBlock.Text = "Not signed in.";
client = null;
}
}
void OnGetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
//Gdy uda nam się podłaczyc do konta skydrive
if (e.Error == null)
{
signInButton1.Visibility = System.Windows.Visibility.Collapsed;
#region Nazwa użytkownika
string firstName = "";
string lastName = "";
if (e.Result.ContainsKey("first_name") ||
e.Result.ContainsKey("last_name"))
{
if (e.Result.ContainsKey("first_name"))
{
if (e.Result["first_name"] != null)
{
firstName = e.Result["first_name"].ToString();
}
}
if (e.Result.ContainsKey("last_name"))
{
if (e.Result["last_name"] != null)
{
lastName = e.Result["last_name"].ToString();
}
}
infoTextBlock.Text =
"Hello, " + firstName +" "+ lastName + "!";
}
else
{
infoTextBlock.Text = "Hello, signed-in user!";
}
#endregion
#region Wszyskite pliki
List<object> data = (List<object>)e.Result["data"];
FilesManager fileManager = new FilesManager();
foreach (IDictionary<string,object> items in data)
{
File file = new File();
file.Name= items["name"].ToString();
fileManager.Files.Add(file.Name);
}
FileList.ItemsSource = fileManager.Files;
#endregion
}
else
{
infoTextBlock.Text = "Error calling API: " +
e.Error.ToString();
}
}
}
Files must be a property, not a field.
Furthermore {Binding Name} must be {Binding} instead, because a string has no Name property.
This has to be a public property:
public ObservableCollection<string> Files;
should be
public ObservableCollection<string> Files {get;set;}
Then your binding will work
I have an wpf mvvm application. I try to write checkbox list control.
I can bind the checkbox list elements.
Added to this issue, I want to get sum of the selected checkbox list elements values.
I added DependencyProperty and bind it to view model property.
But, they dont fire each other.
CheckBoxList User Control Xaml
<ListBox x:Name="ItemsControl" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Text}" IsChecked="{Binding IsSelected, Mode=TwoWay}"
Checked="CheckBox_Checked" Unchecked="CheckBox_Checked" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
CheckBoxList Code Behind
public partial class CheckBoxList : UserControl
{
public CheckBoxList()
{
InitializeComponent();
}
public static readonly DependencyProperty SelectedCheckBoxItemsValueProperty =
DependencyProperty.Register("SelectedCheckBoxItemsValue", typeof(int), typeof(CheckBoxList),
new FrameworkPropertyMetadata(
0,
new FrameworkPropertyMetadata(0, OnSelectedItemsChanged));
public int SelectedCheckBoxItemsValue
{
get { return (int)GetValue(SelectedCheckBoxItemsValueProperty); }
set { SetValue(SelectedCheckBoxItemsValueProperty, value); }
}
private static int GetSelectedCheckBoxItemsValue(DependencyObject obj)
{
return (int)obj.GetValue(SelectedCheckBoxItemsValueProperty);
}
private static void OnSelectedItemsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
CheckBoxList checkboxList = obj as CheckBoxList;
ObservableCollection<ISelectableItem> items = checkboxList.DataContext as ObservableCollection<ISelectableItem>;
foreach (var item in items)
{
item.IsSelected = (GetSelectedCheckBoxItemsValue(obj) & item.Value) != 0;
}
}
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
CheckBoxList checkboxList = sender as CheckBoxList;
ObservableCollection<ISelectableItem> coll = ItemsControl.DataContext as ObservableCollection<ISelectableItem>;
if (coll == null) return;
int count = 0;
foreach (var item in coll)
{
if (item.IsSelected)
{
count += item.Value;
}
}
SelectedCheckBoxItemsValue = count;
}
}
SelectableItem Class
public interface ISelectableItem : INotifyPropertyChanged
{
bool IsSelected { get; set; }
string Text { get; set; }
int Value { get; set; }
string GroupName { get; set; }
}
public class SelectableItem : ISelectableItem
{ ....
ViewModel Property
public int SelectedCheckBoxEnumItemsValue
{
get
{
return _selectedCheckBoxEnumItemsValue;
}
set
{
_selectedCheckBoxEnumItemsValue = value;
NotifyOfPropertyChange("SelectedCheckBoxEnumItemsValue");
}
}
At Binder Class
string selectedItemPropertyName = "Selected" + viewModelProperty.Name + "Value";
var property = viewModelProperties.FirstOrDefault(p => p.Name.Contains(selectedItemPropertyName));
if (property != null)
{
var selectedItemOrValueBinding = new Binding(property.Name)
{
Mode = property.CanWrite ? BindingMode.TwoWay : BindingMode.OneWay,
ValidatesOnDataErrors = Attribute.GetCustomAttributes(property, typeof(ValidationAttribute), true).Any()
};
BindingOperations.SetBinding(control, CheckBoxList.SelectedCheckBoxItemsValueProperty, selectedItemOrValueBinding);
}
Below code solves your problem..
Please Note the segrgation of view models.
<StackPanel>
<TextBlock Text="{Binding Count}"></TextBlock>
<ListBox x:Name="ItemsControl" ItemsSource="{Binding CheckList}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Name="item" Content="{Binding Text}" IsChecked="{Binding IsSelected, Mode=TwoWay}" Command="{Binding CheckboxCheckedCommand}" CommandParameter="{Binding IsChecked, ElementName=item}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MasterViewModel();
}
}
public class MasterViewModel : INotifyPropertyChanged
{
private List<CheckBoxItem> checkList;
private int count;
public int Count
{
get
{
return count;
}
set
{
count = value;
OnPropertyChanged("Count");
}
}
public List<CheckBoxItem> CheckList
{
get
{
return checkList;
}
set
{
checkList = value;
OnPropertyChanged("CheckList");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public MasterViewModel()
{
checkList = new List<CheckBoxItem>();
for (int i = 0; i < 5; i++)
{
CheckBoxItem item = new CheckBoxItem();
item.Text = i.ToString();
item.IsSelected = false;
item.CheckboxCheckedCommand = new RelayCommand(new Action<object>(ExecuteCheckCommand));
checkList.Add(item);
}
}
private void ExecuteCheckCommand(object parameter)
{
if (parameter.GetType() == typeof(bool))
{
bool value = bool.Parse(parameter.ToString());
int val = count;
if (value)
{
val++;
}
else
{
val--;
}
Count = val;
}
}
private void OnPropertyChanged(string p)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
}
}
public class CheckBoxItem : INotifyPropertyChanged
{
private bool isSelected;
private string text;
public string Text
{
get
{
return text;
}
set
{
text = value;
OnPropertyChanged("Text");
}
}
public bool IsSelected
{
get
{
return isSelected;
}
set
{
isSelected = value;
OnPropertyChanged("IsSelected");
}
}
public ICommand CheckboxCheckedCommand
{
get;
set;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string p)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
}
}
public class RelayCommand : ICommand
{
private Action<object> executeCommand;
public RelayCommand(Action<object> executeCommand)
{
this.executeCommand = executeCommand;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
executeCommand(parameter);
}
}