ObservableCollection and DisplayMemberBinding - wpf

I'm trying to fill ListBox by ObservableCollection. But when I add new item nothing displayed, only empty item adding.
There are fragments of my code:
XAML
<ListView ItemsSource="{Binding Points}" SelectedItem="{Binding Point}">
<ListView.View>
<GridView AllowsColumnReorder="False">
<GridViewColumn Header ="X" Width="100" DisplayMemberBinding = "{Binding Path=ValueX, Mode=TwoWay}" />
<GridViewColumn Header ="Y" Width="100" DisplayMemberBinding = "{Binding Path=ValueY, Mode=TwoWay}"/>
</GridView>
</ListView.View>
</ListView>
Window class
var value = new Value();
var viewModel = new ViewModel(value);
DataContext = viewModel;
InitializeComponent();
Value class
private const Point POINT = null;
private readonly ObservableCollection<Point> _points = new ObservableCollection<Point>();
public Value() {
Point = POINT;
Points = _points;
}
public Point Point { get; set; }
public ObservableCollection<Point> Points { get; private set; }
public double ValueX { get; set; }
public int ValueY { get; set; }
ViewModel class
private readonly Value _value;
public ViewModel(Value value) {
_value = value;
}
public Point Point {
get { return _value.Point; }
set {
_value.Point = value;
OnPropertyChanged("Point");
}
}
public ObservableCollection<Point> Points {
get { return _value.Points; }
}
private RelayCommand _addCommand;
public ICommand AddCommand {
get {
if (_addCommand == null) {
_addCommand = new RelayCommand(Add);
}
return _addCommand;
}
}
private void Add(object obj) {
Points.Add(new Point(ValueX, ValueY));
ValueX = 0;
ValueY = 0;
}
public double ValueX {
get {
return _value.ValueX;
}
set {
if(Math.Abs(_value.ValueX - value) < Mathematics.EPSILON) return;
_value.ValueX = value;
OnPropertyChanged("ValueX");
}
}
public int ValueY {
get { return _value.ValueY; }
set {
if(_value.ValueX == value) return;
_value.ValueY = value;
OnPropertyChanged("ValueY");
}
}
and Point class
public class Point {
public readonly double ValueX;
public readonly double ValueY;
public Point(double valueX, double valueY) {
ValueX = valueX;
ValueY = valueY;
}
public override string ToString() {
return (ValueX + " " + ValueY);
}
}
When i try to add new item, new item is added but nothing is displayed. What reason can be here?

Since you bind ItemsSource to ObservableCollection<Point> it means that each item is of a Point type which has ValueX and ValueY declared as fields which are not valid binding source. Change them to properties:
public double ValueX { get; private set; }
public double ValueY { get; private set; }
Besides you use Mode=TwoWay for something that is read only. This should be changed to OneWay. If you want to leave TwoWay binding then remove private from the setter but then also you'll need to change GridViewColumn.CellTemplate to be some TextBox instead of using DisplayMemberBinding which is for display only.

Related

Avalonia.UI ComboBox, no DisplayMemberPath or SelectedValuePath. TemplatedControl

Avalonia.UI ComboBox doesn't have SelectedValuePath & DisplayMemberPath and I'm not skilled enough to implement them.
I have experimented with a TemplatedControl as a work-around because I'm using a TemplatedControl anyway and I don't want to have extra Properties on the ViewModel to handle it.
What I'm trying to archive is to show the items in the ComboBox by DisplayMember but loading/saving by Id. In this test case by Project.ManagerId. It's working but it would be nice not to have to hard-code the Type in that TemplatedControl code behind, like I do right now with "LookupItem". It should be possible to get around that by setting x:DataType="viewModels:LookupItem" or something.
Any ideas?
I have removed most not relevant code.
<Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="using:ChangeTrackingHeaderControls.Controls">
<Design.PreviewWith>
<controls:ChangeTrackingHeaderComboBox />
</Design.PreviewWith>
<Style Selector="controls|ChangeTrackingHeaderComboBox">
<!-- Set Defaults -->
<Setter Property="Template">
<ControlTemplate>
<ComboBox Items="{TemplateBinding Items, Mode=OneWay}"
SelectedItem="{TemplateBinding SelectedItem, Mode=TwoWay}"
SelectedIndex="{TemplateBinding SelectedIndex, Mode=TwoWay}"
ItemTemplate="{TemplateBinding ItemTemplate}"
HorizontalAlignment="Stretch" />
</ControlTemplate>
</Setter>
</Style>
</Styles>
public class ChangeTrackingHeaderComboBox : TemplatedControl
{
private object? _selectedItem;
private int? _selectedValue;
public static readonly DirectProperty<ChangeTrackingHeaderComboBox, object?> SelectedItemProperty =
AvaloniaProperty.RegisterDirect<ChangeTrackingHeaderComboBox, object?>(nameof(SelectedItem),
o => o.SelectedItem,
(o, v) => o.SelectedItem = v,
defaultBindingMode: BindingMode.TwoWay,
enableDataValidation: true);
public static readonly DirectProperty<ChangeTrackingHeaderComboBox, int?> SelectedValueProperty =
AvaloniaProperty.RegisterDirect<ChangeTrackingHeaderComboBox, int?>(nameof(SelectedValue),
o => o.SelectedValue,
(o, v) => o.SelectedValue = v,
defaultBindingMode: BindingMode.TwoWay,
enableDataValidation: true);
public static readonly StyledProperty<IEnumerable> ItemsProperty = AvaloniaProperty
.Register<ChangeTrackingHeaderComboBox, IEnumerable>(nameof(Items));
public static readonly StyledProperty<int> SelectedIndexProperty = AvaloniaProperty
.Register<ChangeTrackingHeaderComboBox, int>(nameof(SelectedIndex));
public static readonly StyledProperty<IDataTemplate> ItemTemplateProperty = AvaloniaProperty
.Register<ChangeTrackingHeaderComboBox, IDataTemplate>(nameof(ItemTemplate));
public object? SelectedItem
{
get => _selectedItem;
set
{
SetAndRaise(SelectedItemProperty, ref _selectedItem, value);
OnSelectedItemChanged();
}
}
public int? SelectedValue
{
get => _selectedValue;
set
{
SetAndRaise(SelectedValueProperty, ref _selectedValue, value);
OnSelectedValueChanged();
}
}
public IEnumerable Items
{
get => GetValue(ItemsProperty);
set => SetValue(ItemsProperty, value);
}
public int SelectedIndex
{
get => GetValue(SelectedIndexProperty);
set => SetValue(SelectedIndexProperty, value);
}
public IDataTemplate ItemTemplate
{
get => GetValue(ItemTemplateProperty);
set => SetValue(ItemTemplateProperty, value);
}
protected override void UpdateDataValidation(AvaloniaProperty property, BindingValueType state, Exception? error)
{
base.UpdateDataValidation(property, state, error);
if (property == SelectedItemProperty)
{
DataValidationErrors.SetError(this, error);
}
if (property == SelectedValueProperty)
{
DataValidationErrors.SetError(this, error);
}
}
private void OnSelectedItemChanged()
{
// LookupItem should not be hard coded
if (SelectedItem is LookupItem selectedItem)
{
if (SelectedValue == selectedItem.Id) return;
if (Items is IEnumerable<LookupItem> items)
{
var selectedItemDisplayMember = selectedItem.DisplayMember;
SelectedValue = items.SingleOrDefault(x => x.DisplayMember == selectedItemDisplayMember).Id;
}
}
}
private void OnSelectedValueChanged()
{
// LookupItem should not be hard coded
if (Items is IEnumerable<LookupItem> items)
{
if (SelectedItem == null)
{
SelectedItem = items.SingleOrDefault(x => x.Id == SelectedValue);
return;
}
if (SelectedItem is LookupItem selectedItem)
{
if (selectedItem.Id == SelectedValue) return;
SelectedItem = items.SingleOrDefault(x => x.Id == SelectedValue);
}
}
}
}
// App.axaml
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:ChangeTrackingHeaderControls.Controls"
xmlns:viewModels="clr-namespace:ChangeTrackingHeaderControls.ViewModels"
x:Class="ChangeTrackingHeaderControls.App">
<Application.Resources>
<DataTemplate x:Key="LookupItemItemTemplate" x:DataType="viewModels:LookupItem">
<ComboBoxItem Content="{CompiledBinding DisplayMember}"
HorizontalContentAlignment="Left"
VerticalContentAlignment="Center" />
</DataTemplate>
</Application.Resources>
<Application.Styles>
<FluentTheme Mode="Light" />
<StyleInclude Source="/Controls/ChangeTrackingHeaderComboBox.axaml" />
</Application.Styles>
</Application>`
// MainWindow
<controls:ChangeTrackingHeaderComboBox Items="{CompiledBinding Managers}"
SelectedValue="{CompiledBinding Project.ManagerId}"
ItemTemplate="{StaticResource LookupItemItemTemplate}" />
// ViewModel
public sealed class MainViewModel : ViewModelBase
{
private Project _project;
public MainViewModel()
{
Managers = new ObservableCollection<LookupItem>();
// Simulating loading Managers from database
for (var i = 1; i < 12; i++)
{
Managers.Add(new LookupItem
{
Id = i,
DisplayMember = $"Manager {i}"
});
}
// One single Project loaded from database
Project = new Project
{
Id = 1,
Name = "Project 1",
ManagerId = Managers.LastOrDefault()?.Id
};
}
public ObservableCollection<LookupItem> Managers { get; }
public Project Project
{
get => _project;
private set
{
if (value == _project) return;
_project = value;
OnPropertyChanged();
}
}
}
// Models
public sealed class Project
{
public int Id { get; set; }
public string Name { get; set; }
public int? ManagerId { get; set; }
}
public sealed class LookupItem
{
public int Id { get; init; }
public string DisplayMember { get; init; }
}```
I have tried to use x:DataType="viewModels:LookupItem" and also implemented StyledProperty<Type> but no succcess.
On the ViewModel instances bound to the ComboBox's Items property, override ToString() and return the value you want displayed in the open drop down.

WPF Update count of item when button is pushed

new to WPF and programming here I am trying to update an item in a ListView when a button is pushed if the item already exists in that ListView, for example a user inputs CAR and CAR is already in the ListView the CAR count should go from 1 to 2.
This is my InventoryItem class:
public class InventoryItem
{
public string Name { get; set; }
public int Count { get; set; }
}
Here is my ViewModel
public class ViewModel : ViewModelBase
{
private InventoryItem _item;
private int _count;
private ObservableCollection<InventoryItem> _inventoryItems;
private ICommand _addItem;
public InventoryItem Item
{
get
{
return _item;
}
set
{
_item = value;
NotifyPropertyChanged("Item");
}
}
public int Count
{
get { return _count; }
set { _count = value; NotifyPropertyChanged("Count"); }
}
public ObservableCollection<InventoryItem> InventoryItems
{
get
{
return _inventoryItems;
}
set
{
_inventoryItems = value;
NotifyPropertyChanged("Items");
}
}
public ICommand AddItem
{
get
{
if (_addItem == null)
{
_addItem = new RelayCommand(ParamArrayAttribute => this.Submit(), null);
}
return _addItem;
}
}
public ViewModel()
{
Item = new InventoryItem();
InventoryItems = new ObservableCollection<InventoryItem>();
InventoryItems.CollectionChanged += new NotifyCollectionChangedEventHandler(InventoryItems_CollectionChanged);
}
void InventoryItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
NotifyPropertyChanged("Items");
NotifyPropertyChanged("Count");
}
private void Submit()
{
if (InventoryItems.Any(p => p.Name == Item.Name))
{
InventoryItems.First(x => x.Name == Item.Name).ItemCount++;
}
else
{
InventoryItems.Add(Item);
}
}
}
Here is my View
<ListView x:Name="listBox" ItemsSource="{Binding InventoryItems}" Grid.Row="0" HorizontalAlignment="Stretch" Height="Auto" Margin="10,10,10,60" VerticalAlignment="Stretch">
<ListView.Resources>
<Style TargetType="GridViewColumnHeader">
<Setter Property="Visibility" Value="Collapsed"/>
</Style>
</ListView.Resources>
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Name}" Width="Auto"/>
<GridViewColumn DisplayMemberBinding="{Binding ItemCount}" Width="Auto"/>
</GridView>
</ListView.View>
</ListView>
Whenever an item that exists in the list is typed in it appears that the InventoryItems ObservableCollection is being updated however InventoryItems_CollectionChanged event is not being fired so the ListView is not being updated. Isn't the collection changing so that event should be fired to update the ListView or am I not understanding the Binding and the event?
You need to notify about property changes in the InventoryItem class to update the changes of ItemCount in the ListView.
Quick solution:
public class InventoryItem : ViewModelBase
{
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
NotifyPropertyChanged(nameof(Name));
}
}
}
private string _name;
public int ItemCount
{
get { return _itemCount; }
set { _itemCount = value; NotifyPropertyChanged(nameof(ItemCount));
}
}
private int _itemCount;
}
}
The ObservableCollection class already contains handling of INotifyCollectionChanged.
You only need this line for the ObservableCollection. You can remove everything else that has to do with "InventoryItems" and the collection in your ViewModel.
public ObservableCollection<InventoryItem> InventoryItems { get; } = new ObservableCollection<InventoryItem>();
Also: When you add an item to the collection you need to create a new item. Otherwise you are adding the same object, that will not work.
This is my reduced ViewModel to how I think you want it to work:
public class ViewModel : ViewModelBase
{
private ICommand _addItem;
public string InputName
{
get { return _inputName; }
set
{
if (_inputName != value)
{
_inputName = value;
NotifyPropertyChanged(nameof(InputName));
}
}
}
private string _inputName;
public ObservableCollection<InventoryItem> InventoryItems { get; } = new ObservableCollection<InventoryItem>();
public ICommand AddItem
{
get
{
if (_addItem == null)
{
_addItem = new RelayCommand(ParamArrayAttribute => this.Submit(), null);
}
return _addItem;
}
}
private void Submit()
{
if (InventoryItems.Any(p => p.Name == InputName))
{
InventoryItems.First(x => x.Name == InputName).ItemCount++;
}
else
{
InventoryItems.Add(new InventoryItem() { Name = InputName, ItemCount = 1 });
}
}
}
To complete the picture, I have added following XAML for test:
<TextBox Text="{Binding InputName}" MinWidth="100" Margin="5"/>
<Button Content="Add" Command="{Binding AddItem}" Margin="5"/>

Binding Custom Object to WPF Combobox

I have a combobox that has an items source of type ObservableCollection<Clinic>
<ComboBox ItemsSource="{Binding Source={StaticResource ClinicList}}" DisplayMemberPath="Name" SelectedValue="{Binding Path=Name}" SelectedValuePath="Name"></ComboBox>
This combobox is within a ListView that is bound from EmployeeClinics.
public class Employee{
public ObservableCollection<Clinic> EmployeeClinics { get; set; }
}
When I launch the app I see the appropriate clinics. And the drop down seems to show the correct options, but when I update them, only the Name updates and not the ClinicId (it keeps previous ClinicId).
Edit: Similarly when I add a new clinic to the list and select it from the options, it's Id is 0 when I look at the collection.
Here is my clinic model.
public class Clinic {
public int ClinicId { get; set; }
public string _name { get; set; }
public string Name {
get {
return _name;}
set {
if (_name != value) {
_name = value;
}
}
}
}
UPDATE: Thanks #AyyappanSubramanian. I am making headway. I have updated my Objects
public class Employee{
public ObservableCollection<ClinicView> EmployeeClinics { get; set; }
}
public class ClinicView {
private Clinic selectedClinic;
public Clinic SelectedClinic {
get { return selectedClinic; }
set {
selectedClinic = value;
selectedClinicId = selectedClinic.ClinicId;
}
}
private int selectedClinicId;
public int SelectedClinicId {
get { return selectedClinicId; }
}
}
XAML:
<ComboBox ItemsSource="{Binding Source={StaticResource ClinicList}}" DisplayMemberPath="Name" SelectedItem="{Binding SelectedClinic}"></ComboBox>
Changing the drop downs now properly changes the underlying object and updates the list as desired. Now my only issue is that the comboboxes don't display the current object, just show as blank on start. I've messed around with SelectedValue and Path with no luck. Any suggestions?
Refer the below code. You can use SelectedItem to get both the ID and Name in one SelectedObject. Get only ID using SelectedValue.
<ComboBox ItemsSource="{Binding Clinics}" DisplayMemberPath="ClinicName"
SelectedValuePath="ClinicId" SelectedValue="{Binding SelectedClinicId}"
SelectedItem="{Binding SelectedClinic}"/>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
class Clinic
{
public int ClinicId { get; set; }
public string ClinicName { get; set; }
}
class ViewModel
{
public ObservableCollection<Clinic> Clinics { get; set; }
public ViewModel()
{
Clinics = new ObservableCollection<Clinic>();
for (int i = 0; i < 10; i++)
{
Clinics.Add(new Clinic() { ClinicId=i+1,ClinicName="MyClinic"+(i+1) });
}
}
private int selectedClinicId;
public int SelectedClinicId
{
get { return selectedClinicId; }
set
{
selectedClinicId = value;
}
}
private Clinic selectedClinic;
public Clinic SelectedClinic
{
get { return selectedClinic; }
set
{
selectedClinic = value;
MessageBox.Show("ID:"+selectedClinic.ClinicId.ToString()+" "+"Name:"+selectedClinic.ClinicName);
}
}
}

WPF MVVM User Control binding problem

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);
}
}

Binding to ItemsSource not working until visual element is manually inspected (MVVM)

I have the Xaml which should basically bind a set of ContextualButtons for a selected tab's viewmodel to the ItemsSource property of the ToolBar. For some reason, this binding is not actually occuring unless I use Snoop to inspect the element manually...It seems that the act of snooping the element is somehow requerying the binding somehow.
Does anyone know what I might be doing wrong here? This behavior is the same if I use a Listbox as well, so I know it is something that I am doing incorrectly...but I am not sure what.
SelectedView is a bound property to the selected view from a Xam Tab control.
XAML
<ToolBar DataContext="{Binding SelectedView.ViewModel}"
ItemsSource="{Binding ContextualButtons}" >
<ToolBar.ItemTemplate>
<DataTemplate>
<!-- <Button ToolTip="{Binding Name}"-->
<!-- Command="{Binding Command}">-->
<!-- <Button.Content>-->
<!-- <Image Width="32" Height="32" Source="{Binding ImageSource}"/>-->
<!-- </Button.Content>-->
<!-- </Button>-->
<Button Content="{Binding Name}"/>
</DataTemplate>
</ToolBar.ItemTemplate>
</ToolBar>
Code
public class TestViewModel : BaseViewModel, IBulkToolViewModel
{
public TestViewModel()
{
ContextualButtons = new ObservableCollection<IContextualButton>()
{
new ContextualButton("Test Button",
new DelegateCommand<object>(
o_ => Trace.WriteLine("Called Test Button")), String.Empty)
};
}
public string Key { get; set; }
private ObservableCollection<IContextualButton> _contextualButtons;
public ObservableCollection<IContextualButton> ContextualButtons
{
get { return _contextualButtons; }
set
{
if (_contextualButtons == value) return;
_contextualButtons = value;
//OnPropertyChanged("ContextualButtons");
}
}
}
public partial class TestView : UserControl, IBulkToolView
{
public TestView()
{
InitializeComponent();
}
public IBulkToolViewModel ViewModel { get; set; }
}
public class ContextualButton : IContextualButton
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public ICommand Command { get; set; }
public string ImageSource { get; set; }
public ContextualButton(string name_, ICommand command_, string imageSource_)
{
Name = name_;
Command = command_;
ImageSource = imageSource_;
}
}
public class BulkToolShellViewModel : BaseViewModel, IBaseToolShellViewModel, IViewModel
{
private IBulkToolView _selectedView;
public IBulkToolView SelectedView
{
get
{
return _selectedView;
}
set
{
if (_selectedView == value) return;
_selectedView = value;
OnPropertyChanged("SelectedView");
}
}
public ObservableCollection<IBulkToolView> Views { get; set; }
public DelegateCommand<object> AddViewCommand { get; private set; }
public DelegateCommand<object> OpenPortfolioCommand { get; private set; }
public DelegateCommand<object> SavePortfolioCommand { get; private set; }
public DelegateCommand<object> GetHelpCommand { get; private set; }
public BulkToolShellViewModel(ObservableCollection<IBulkToolView> views_)
: this()
{
Views = views_;
}
public BulkToolShellViewModel()
{
Views = new ObservableCollection<IBulkToolView>();
AddViewCommand = new DelegateCommand<object>(o_ => Views.Add(new TestView
{
ViewModel = new TestViewModel()
}));
OpenPortfolioCommand = new DelegateCommand<object>(OpenPortfolio);
SavePortfolioCommand = new DelegateCommand<object>(SavePortfolio);
GetHelpCommand = new DelegateCommand<object>(GetHelp);
}
private void GetHelp(object obj_)
{
}
private void SavePortfolio(object obj_)
{
}
private void OpenPortfolio(object obj_)
{
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged()
{
throw new NotImplementedException();
}
public void RaisePropertyChanged(string propertyName)
{
throw new NotImplementedException();
}
public string this[string columnName]
{
get { throw new NotImplementedException(); }
}
public string Error { get; private set; }
public AsyncContext Async { get; private set; }
public XmlLanguage Language { get; private set; }
public string Key { get; set; }
}
Thanks!
Why does BulkToolShellViewModel have its own PropertyChanged event along with RaisePropertyChanged methods that do nothing? Shouldn't it inherit this functionality from BaseViewModel? Perhaps the UI is attaching to BulkToolShellViewModel.PropertyChanged rather than BaseViewModel.PropertyChanged and is never being notified of changes.

Resources