Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

c# - WPF Combox data updated but UI not updated - Updated code

Here is the code:

MainWindow.xaml

<ComboBox Grid.Column="1" Margin="2" VerticalContentAlignment="Center" ItemsSource="{Binding Path=LowDLane, Mode=OneWay}"
                                  SelectedIndex="{Binding Path=CurrentLowDLaneIndex, Mode=TwoWay, FallbackValue=0}"
                                  DropDownOpened="onLowDLaneDropDownOpened"
                                  SelectionChanged="onLowDLaneChanged">
</ComboBox>

MainWindow.xaml.cs

public partial class MainWindow : Window
{

    public MainWindow(ViewModel model)
    {
        InitializeComponent();
        this.DataContext = model;
    }

    private void onLowDLaneDropDownOpened(object aSender, EventArgs aE)
    {
        ((ViewModel)this.DataContext).openedDropDown();
    }
}

ViewModel.cs Updated

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChangedHandler;

    public List<string> LowDLane
    {
        get { return mLowDLane; }
        set
        {
            mLowDLane = value;
           PropertyChangedHandler.raise(this, ()=> LowDLane);
        }
    }
    public void openedDropDown()
    {
        LowDLane = new List<string> { "1", "2", "3", "4", "5", "6", "7", "8"};
    }

}

In other file PropertyChangedEventHandler is defined:

namespace System.ComponentModel

{

public delegate void PropertyChangedEventHandler(object sender, PropertyChangedEventArgs e);

}

Represents the method that will handle the System.ComponentModel.INotifyPropertyChanged.PropertyChanged event raised when a property is changed on a component.

PropertyChangedEventHandler works well in other places so I don't think this is the problem here.

I created ViewModel object in other file, and passed it to MainWindow. When I run the application, I can see the LowDLane property is updated, but the UI is not updated.

I have looked many similar questions, but none of them solved my issue. Can someone help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should call NotifyPropertychanged method of yours inside your setter

public List<string> LowDLane
{
      get { return mLowDLane; }
      set
      {
         mLowDLane = value;
         NotifyPropertyChanged("LowDLane"); // here
      }
}

For more details see here

And you may want to use CallerMemberName Attribute in your code see here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...