logo
down
shadow

Bound combobox: text disappearing after sorting the source list of strings


Bound combobox: text disappearing after sorting the source list of strings

By : Zeeshan Anis
Date : October 15 2020, 11:12 PM
To fix the issue you can do Hey I think I have a solution for you. Just add the following line to your Datagrid definition
code :


Share : facebook icon twitter icon
How to change the Combobox.Text property when Combobox is bound to data?

How to change the Combobox.Text property when Combobox is bound to data?


By : user2128353
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Honestly this is one of the things I hate about Windows Forms databinding. In WPF you would not bind to the objects directly, you'd bind to a "ViewModel" object which encapsulated this view logic you have and bind to it instead.
My workaround to all of this would be to just not use databinding for this case at all and manually populate the items as needed. I can understand why you might be having this problem. If you had updated your underlying bound object's .Text (or whatever causes ToString() to display the value), you would probably see the new value you'd set, but that upsets the semantics of your underlying objects, which is Not A Good Thing.
CollectionViewSource sorting only the first time it is bound to a source

CollectionViewSource sorting only the first time it is bound to a source


By : user2261946
Date : March 29 2020, 07:55 AM
Any of those help Great question and an interesting observation. Upon closer inspection, it appears that the DataGrid clears sort descriptions of a previous ItemsSource before a new one is set. Here is its code for OnCoerceItemsSourceProperty:
code :
private static object OnCoerceItemsSourceProperty(DependencyObject d, object baseValue)
{
    DataGrid grid = (DataGrid) d;
    if ((baseValue != grid._cachedItemsSource) && (grid._cachedItemsSource != null))
    {
        grid.ClearSortDescriptionsOnItemsSourceChange();
    }
    return baseValue;
}
lstLevel.SelectionChanged +=
    (sender, e) =>
    {
        levels.ToList().ForEach((p) =>
        {
            CollectionViewSource.GetDefaultView(p.Players)
                .SortDescriptions
                .Add(new SortDescription("Name", ListSortDirection.Ascending));
        });
    };

lstLevel.ItemsSource = levels;
<!-- Players data, with sort on the Name column -->
<StackPanel Grid.Column="1">
    <Label>DataGrid:</Label>
    <DataGrid Name="lstPlayers" AutoGenerateColumns="False"
        CanUserSortColumns="False"
        ItemsSource="{Binding ElementName=lstLevel, Path=SelectedItem.Players}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name"
                        Binding="{Binding Path=Name, Mode=TwoWay}"
                        Width="*" />
            <DataGridTextColumn Header="Age"
                        Binding="{Binding Path=Age, Mode=TwoWay}"
                        Width="80">
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
</StackPanel>

<StackPanel Grid.Column="2">
    <Label>ListBox:</Label>
    <ListBox ItemsSource="{Binding ElementName=lstLevel, Path=SelectedItem.Players}" DisplayMemberPath="Name" />
</StackPanel>
lstLevel.SelectionChanged +=
    (sender, e) =>
    {
        levels.ToList().ForEach((p) =>
        {
            CollectionViewSource.GetDefaultView(p.Players)
                .SortDescriptions
                .Add(new SortDescription("Name", ListSortDirection.Ascending));
        });
    };
lstLevel.ItemsSource = levels;
Selection of combobox bound to observablecollection of string gets lost after changing strings

Selection of combobox bound to observablecollection of string gets lost after changing strings


By : user3021047
Date : March 29 2020, 07:55 AM
hop of those help? You could wrap the value of the string, but there might be better methods.
code :
public class WrappedValue<T> : INotifyPropertyChanged where T : IEquatable<T>
{
    private T _value;
    public T Value
    {
        get { return _value; }
        set
        {
            if (_value == null || !_value.Equals(value))
            {
                _value = value;
                OnPropertyChanged("Value");
            }
        }
    }

    public WrappedValue() { }

    public WrappedValue(T value)
    {
        Value = value;
    }

    public static implicit operator T(WrappedValue<T> a)
    {
        return a.Value;
    }

    public static implicit operator WrappedValue<T>(T a)
    {
        return new WrappedValue<T>(a);
    }

    private void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
ObservableCollection<WrappedValue<string>> myList = new ObservableCollection<WrappedValue<string>>();
myList.Add("A");
myList.Add("B");
myComboBox.ItemsSource = myList;
myList[0].Value = "C";
How to enforce distinct selections when multiple ComboBox's are bound to a common source?

How to enforce distinct selections when multiple ComboBox's are bound to a common source?


By : David Taub
Date : March 29 2020, 07:55 AM
This might help you what about using a RowFilter? this of course just work if you use a new DataView instead of the DefaultView. you could create 4 DataView and set the RowFilter when ever a SelectedItem changed.
look at my answer in this thread. the sample is for listview, but you can easy achieve the same with combobox
code :
public class MyTest
{
    private DataTable dt;

    public BindingListCollectionView View1 { get; set; }
    public BindingListCollectionView View2 { get; set; }
    public BindingListCollectionView View3 { get; set; }
    public BindingListCollectionView View4 { get; set; }

    private string _selected1;
    public string Selected1
    {
        get { return _selected1; }
        set { _selected1 = value;
            this.UpdateFilter();
        }
    }

    private void UpdateFilter()
    {
        this.View1.CustomFilter = GetFilter(this.Selected2, this.Selected3, this.Selected4);
        this.View2.CustomFilter = GetFilter(this.Selected1, this.Selected3, this.Selected4);
        this.View3.CustomFilter = GetFilter(this.Selected1, this.Selected2, this.Selected4);
        this.View4.CustomFilter = GetFilter(this.Selected1, this.Selected2, this.Selected3);
    }

    private string GetFilter(string selected2, string selected3, string selected4)
    {
        var filter = "";

        if (!string.IsNullOrWhiteSpace(selected2))
            filter = "Name <> '" + selected2 + "' and ";

        if(!string.IsNullOrWhiteSpace(selected3))
            filter += "Name <> '" + selected3 + "' and ";

        if (!string.IsNullOrWhiteSpace(selected4))
            filter += "Name <> '" + selected4 + "' and ";

        if (!string.IsNullOrWhiteSpace(filter))
            filter = filter.Substring(0, filter.Length - 4);

        return filter;
    }

    private string _selected2;
    public string Selected2
    {
        get { return _selected2; }
        set { _selected2 = value;
        this.UpdateFilter();
        }
    }

    private string _selected3;
    public string Selected3
    {
        get { return _selected3; }
        set { _selected3 = value;
        this.UpdateFilter();
        }

    }
    private string _selected4;
    public string Selected4
    {
        get { return _selected4; }
        set { _selected4 = value;
        this.UpdateFilter();
        }

    }

    public MyTest()
    {
        this.dt = new DataTable();
        this.dt.Columns.Add("Name");

        for (int i = 0; i < 15; i++)
        {
            var row = dt.NewRow();
            row["Name"] = "Name " + i;
            dt.Rows.Add(row);
        }

        View1 = new BindingListCollectionView(new DataView(dt));
        View2 = new BindingListCollectionView(new DataView(dt));
        View3 = new BindingListCollectionView(new DataView(dt));
        View4 = new BindingListCollectionView(new DataView(dt));
    }
}
public partial class ComboxFour : UserControl
{
    private MyTest data;
    public ComboxFour()
    {
        this.data = new MyTest();
        InitializeComponent();
        this.DataContext = data;
    }
}
<StackPanel Orientation="Horizontal">
    <ComboBox Width="100" Height="30" SelectedValue="{Binding Selected1}" ItemsSource="{Binding View1}" DisplayMemberPath="Name" SelectedValuePath="Name"/>
    <ComboBox Width="100" Height="30" SelectedValue="{Binding Selected2}" ItemsSource="{Binding View2}" DisplayMemberPath="Name" SelectedValuePath="Name"/>
    <ComboBox Width="100" Height="30" SelectedValue="{Binding Selected3}" ItemsSource="{Binding View3}" DisplayMemberPath="Name" SelectedValuePath="Name"/>
    <ComboBox Width="100" Height="30" SelectedValue="{Binding Selected4}" ItemsSource="{Binding View4}" DisplayMemberPath="Name" SelectedValuePath="Name"/>
</StackPanel>
Binding ComboBox with Generic List so that value of combobox item represents bound object

Binding ComboBox with Generic List so that value of combobox item represents bound object


By : Genus88
Date : March 29 2020, 07:55 AM
this will help Use cmb.SelectedItem instead which returns an object, cast it as MyClass and do not set SelectedValuePath at all
Related Posts Related Posts :
  • weight update of one random layer in multilayer neural network using backpagation?
  • Find most recent date in a list of objects on LocalDate property using Java 8 stream
  • deflateSetDictionary usage
  • Getting Me using Azure OAuth 2 Token
  • How do I get an Aspara Video playauth?
  • Avoiding memory leaks with Commanded in an aggregate that doesn't produce an event
  • Terraform: How to get a boolean from interpolation?
  • How can I disable shift (or any modifier) for some keys but not for others?
  • How to access component model from outside
  • Formatting decimal output when multiplying all numerical values in a string?
  • How to solve the numerical instability to a solution of a system of ordinary differential equations
  • How can I determine if a row has changed?
  • Inherited software that's built on Visual FoxPro, How can I access the source files and edit the program as needed?
  • Problem accessing orion-psb-image-R5.4 on FIWARE Lab using ssh
  • Check if List of Matrix Indexes are adjacent
  • View availability message on summary page Cart
  • Spring AMQP RabbitMQ RPC - Queue with with some messages that do not expect a response
  • App Pool Login Failed Message in New Acumatica Version
  • New-AzureRmSqlDatabaseImport does not accept a DatabaseMaxSizeBytes greater than 5GB
  • How to get the list of queues from a server?
  • Maxima plot discrete data with 3 columns
  • Referencing field from input in a Logstash filter
  • Chapel : Understanding lifetime of managed classes with zip and user-defined iterators
  • Compile With Static Library Using GNAT
  • Is there a way to receive most messages out of the standard SQS Queue? [NOT FIFO]
  • Remove shadow from XFCE panel
  • How do I serialize TransactionBuilder
  • How to disable Rule: one-line in TSLint
  • Automatically Ignore @OneToMany, @ManyToOne
  • Accidently renamed libc.so.6 and cannot chroot within rescue mode
  • A proper way to serialize/deserialize Xodus-dnq entity
  • How to hide the overlays in A frame?
  • PRelue is not supperted with mmdnn?
  • JasperReports: How to pass parameter to subReport
  • Is there built-in web analytics tool in Liferay?
  • 'if' scenario in an equation. How do I implement it?
  • Uncaught [CKEDITOR.editor] The instance "html" already exists
  • Trimming variable in CLLE
  • Slot not being passed from action to layout in Symfony 1.4
  • Are there any disadvantages of using C# 3.0 features?
  • How to download paypal transactions using some API
  • Microsoft CRM could not log you on to the system. Make sure your user record
  • Good acceleration structure for ray sphere tests with spheres that move
  • Draw formatted rich text
  • How can I sum values in column based on the value in another column?
  • JBoss eventually stops responding to request, but no OOME
  • Prevent inline-block from wrapping on white-space: pre?
  • Neural Network Recommendation Engine
  • Getting the return value of an exec process
  • Dynamics CRM: Create users with specific GUIDs
  • Languages used to write programs for satellite-missions?
  • is it possible to use only two semaphores to synchronise three or more threads?
  • Opengl ES - drawing a plane of multiple vertices
  • Make Aptana never use Windows line endings
  • Stub property and save other behaviour
  • What would you call "callback" or "closure" in general?
  • Drag a bezier curve to edit it
  • Archive/Compress Command FTP Through Terminal?
  • how can I use curly braces in a mysql query?
  • or operator in vbscript
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org