Home > Net >  Set Combobox value to a default value depending on computers printer settings
Set Combobox value to a default value depending on computers printer settings

Time:10-08

I have a ComboBox on a WPF application that contains all the printers attached to a computer. The printers are getting to the ComboBox correctly and I am also capturing the default printer. Now what I want to do is set the default or selected value on the ComboBox to the default printer.

I am getting the list of printers and the default with this

private void GetPrinterList()
{
    var server = new PrintServer();
    var queues = server.GetPrintQueues(new[] {EnumeratedPrintQueueTypes.Shared,
        EnumeratedPrintQueueTypes.Connections});

    string defaultPrinter = GetDefaultPrinter();
    
    Printers = new ObservableCollection<Printer>();

    foreach (var item in queues)
    {
        Printers.Add(new Printer { Name = item.FullName });
    }

    queues = server.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local });

    foreach (var item in queues)
    {
        Printers.Add(new Printer { Name = item.FullName });
    }

                
    var defPrinter = Printers.FirstOrDefault(i => i.Name == defaultPrinter);
    if (defPrinter != null)
    {
        //NOTE Modified example after posting because @ASh
        //made aware (in comments) I had an error in code.
        CurrentDefaultPrinter = defPrinter.Name.ToString();
    }
}

On the XAML side I have tried binding both the SelectedValue and SelectedValuePath to the CurrentDefaultPrinter but neither show the selected value in the ComboBox. What am missing to make this work?

<ComboBox 
    Width="150" 
    Height="35" 
    Margin="0,0,0,2"
    DisplayMemberPath="Name"
    FontSize="18" 
    SelectedItem="{Binding CurrentDefaultPrinter, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
    ItemsSource="{Binding Printers}" />

I did find this solution that is similar to what I am trying to do but isn't close enough for me to solve my issue.

Setting a default selected item in ComboBox in WPF MVVM application

Note Both my code and XAML have been modified after posting because it was pointed out there was an error in my code. However, after the modification I am still not getting the ComboBox to show the default printer with updated code.

CodePudding user response:

don't bind SelectedValue or SelectedValuePath, only SelectedItem:

SelectedItem="{Binding CurrentDefaultPrinter}"

note that SelectedItem should be present in ItemsSource collection. so it should have the same type as items in that collection, not string. additionally it should raise PropertyChanged event (from INPC interface)

public Printer CurrentDefaultPrinter { get; set; }

CurrentDefaultPrinter = Printers.FirstOrDefault(i => i.Name == defaultPrinter);
  • Related