开发者

C#: Bind TextBox to SelectedValue

I have a List<> of objects that I have bound to a ListBox. I then want to bind properties of the SelectedValue to various TextBoxes. The behavior is very screwy though.

When binding the Name (a string) that is used as the DisplayMember for the ListBox, it doesn't update the ListBox and if I try to refresh the binding on the TextCha开发者_如何转开发nged event, it doesn't update until the selection changes and then it has problems switching the selection.

When binding Balance (a decimal) it changes all of them (or, possibly, the change is being applied when I change the selection, but it is actually changing the data, not just not updating).

To be clear, I am using C#.NET and not ASP.


Assuming WPF, a quick sample:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <ListBox x:Name="list" 
                 ItemsSource="{Binding}"
                 DisplayMemberPath="Name"/>
        <TextBox Text="{Binding ElementName=list, Path=SelectedItem.Name}"
                 Grid.Row="1"/>
        <TextBox Text="{Binding ElementName=list, Path=SelectedItem.Val}"
                 Grid.Row="2" />
    </Grid>
</Window>

namespace WpfApplication1 {
    public class Thing : INotifyPropertyChanged {
        private string _name;
        private double _val;

        public string Name {
            get { return _name; }
            set {
                _name = value;
                OnPropertyChanged("Name");
            }
        }

        public double Val {
            get { return _val; }
            set {
                _val = value;
                OnPropertyChanged("Val");
            }
        }

        protected void OnPropertyChanged(string propertyName) {
            PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
            if (propertyChanged != null) {
                propertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();

            DataContext = new List<Thing> { new Thing { Name = "A", Val = 1.0 }, new Thing { Name = "B", Val = 2.0 } };
        }
    }
}


I found the solution at Switch on the Code. Basically, I need to use the BindingList collection instead of just List.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜