0

I have a printer model:

public class Printer: BindableBase
    {
        private bool isDefault = false;
        public string Name { get; set; }
        public bool IsDefault
        {
            get { return isDefault; }
            set { SetProperty(ref isDefault, value); }
        }
    }

and a printer viewmodel:

public class PrinterViewModel: BindableBase
    {
        public ObservableCollection<Printer> Printers { get; set; }

        public PrinterViewModel()
        {
            Printers = new ObservableCollection<Printer>();

            LoadPrinters();
        }

        public void LoadPrinters()
        {
            Printers.Add(new Printer { Name = "HP" });
            Printers.Add(new Printer { Name = "Sony" });
            Printers.Add(new Printer { Name = "Samsung" });
            Printers.Add(new Printer { Name = "LG" });
            Printers.Add(new Printer { Name = "Toshiba" });
        }
    }

and a list box with an Itemtemplate so each item shows up with its Name in a TextBlock and a Button to change "IsDefault" property of this item:

<ListBox ItemsSource="{Binding Printers }"> 
 <ListBox.ItemTemplate> 
  <DataTemplate> 
   <StackPanel Orientation="Horizontal"> 
    <TextBlock Text="{Binding Name}"/> 
    <Button x:Name="SetDefault" Content="Set as Default"/> 
   </StackPanel> 
  </DataTemplate> 
 </ListBox.ItemTemplate> 
</ListBox>

Now, I want to change the "IsDefault" property of any item when its "SetDefault" button is clicked to 'true' and 'false' for all other items. how can I do that?

Thx in advance for any help.

  • 1
    In your `PrinterViewModel`, create a command (DelegateCommand/RelayCommand) that will be accessible through a property and thus can and should be bound against all buttons (this binding will have to specify the ListBox itself as source "DataContext.NameOfTheCommandProperty" as binding path. Additionally, bind the CommandParameter of each button bind against the item (Printer) itself. The implemenation of the command in the viewmodel will just be a method that receives the Printer instance from the CommandParameter of the pressed button. (1/2) –  Jul 06 '19 at 17:15
  • 1
    (2/2) From there it should be easy to set IsDefault for the whole printer collection to false, and set IsDefault for the Printer instance provided to the command method to true... –  Jul 06 '19 at 17:15
  • Some reading stuff with regard to Delegate/RelayCommand (containing further links worth to follow): https://stackoverflow.com/questions/14180688/difference-between-delegatecommand-relaycommand-and-routedcommand Some reading stuff about possible ways of binding against the ItemsControl (such as ListBox) from within an ItemTemplate: https://stackoverflow.com/questions/30225600/how-to-bind-to-a-source-inside-a-listbox-different-from-the-itemssource-already –  Jul 06 '19 at 17:19

0 Answers0