0

I'm using WPF C#

I want to show DisplayMemberPath and SelectedValuePath in a Combobox item but when the user clicked on one of the Combobox items, then on the Combobox selected item showing just SelectedValue

Like this Emulated picture : enter image description here

My Model:

    public partial class CST
{
    public string Tafcode { get; set; }//ID
    public string Esm { get; set; }//Name

    public string Shoy => $"{Tafcode}  {Esm}";
}

CS :

  var quer_ITM = dbms.Database.SqlQuery<CST>("SELECT Tafcode , Esm FROM CST").ToList();

        cmb.ItemsSource = quer_ITM;
        cmb.DisplayMemberPath = "Shoy"; //Merg of Esm + Tafcode
        cmb.SelectedValuePath = "Tafcode";//The Primary Key 112-1-1

XAML:

 <ComboBox x:Name="cmb"  Margin="0,312,202,0" VerticalAlignment="Top" Height="22" FlowDirection="RightToLeft"  FontFamily="/Negin;component/NT/#IRANSans" IsEditable="True" Background="#FFCCFFFF" HorizontalAlignment="Right" Width="402">
       
    </ComboBox>

I have no error in the up lines, just I don't know how to do that

Please Help ?

  • You can do this via templating. https://stackoverflow.com/questions/4672867/can-i-use-a-different-template-for-the-selected-item-in-a-wpf-combobox-than-for – Andy Jul 14 '21 at 19:07

2 Answers2

0

I believe you cannot directly define the manipulation operator with the same class members. You either have to write a small helper function to do this Try changing your code to cmb.DisplayMemberPath = $"{Tafcode} {Esm}";

SRK45
  • 43
  • 5
0

You could replace the DisplayMemberPath with an ItemTemplate:

cmb.ItemsSource = dbms.Database.SqlQuery<CST>("SELECT Tafcode , Esm FROM CST").ToList();
...
<ComboBox x:Name="cmb"  Margin="0,312,202,0" VerticalAlignment="Top" Height="22" FlowDirection="RightToLeft" 
        FontFamily="/Negin;component/NT/#IRANSans" IsEditable="True" Background="#FFCCFFFF" HorizontalAlignment="Right" Width="402"
        SelectedValuePath="SelectedValuePath">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Shoy}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

...and override the ToString() method of your class:

public partial class CST
{
    public string Tafcode { get; set; }
    public string Esm { get; set; }

    public string Shoy => $"{Tafcode}  {Esm}";

    public override string ToString() => Tafcode;
}
mm8
  • 163,881
  • 10
  • 57
  • 88