开发者

How to get TextBox inside DataTemplate in a ListBox to notify the ViewModel on value change

开发者 https://www.devze.com 2023-01-17 06:16 出处:网络
What I need to find is when a textbox\'s value is changing or the dropdown\'s value changes inside my datatemplate item, I need to be notified in my ViewModel.cs.

What I need to find is when a textbox's value is changing or the dropdown's value changes inside my datatemplate item, I need to be notified in my ViewModel.cs.

So basically as a user edits a textbox inside the listbox, the viewmodel will be notified as the values are changing.

The reason is I need to go through all my Entries and update something as items inside the listbox's datatemplate change.

Any suggetion?

I have the following in my XAML.

<ListBox x:Name="EntriesListBox"
         ItemsSource="{Binding Path=Entries}"
         Grid.Row="1">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <ComboBox x:Name="EntriesPropertyName"
                          Width="215"
                          Margin="0,0,5,0"
                          SelectedItem="{Binding Path=Property, Mode=TwoWay}"
                          ItemsSource="{Binding Source={StaticResource DataContextProxy},Path=DataSource.EntityTypeProperties}" />               
                <TextBox x:Name="EntriesPropertyValue"
                         Width="215"
                         Margin="0,0,5,0"
                         Text="{Binding Path=Value, Mode=TwoWay, BindsDirectlyToSource=True}" />                                   
       开发者_JS百科     </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

The following is in my VM (ViewModel.cs)

public ObservableCollection<Entry> Entries { get; set; }

The following is in my business object (Entry.cs)

public class Entry
{
  public PropertyItem Property { get; set; }
  public string Value { get; set; }
}


On your binding, set the UpdateSourceTrigger... Also implement INotifyPropertyChanged


Provided that you have setup your view model class properly (by implementing INotifyPropertyChanged), following is what you may want to do:

 <TextBox x:Name="EntriesPropertyValue"
                         Width="215"
                         Margin="0,0,5,0"
                         Text="{Binding Path=Value, Mode=TwoWay, BindsDirectlyToSource=True, UpdateSourceTrigger=PropertyChanged}" /> 


This seems to work. Any reason not to do it this way?

private void EntriesPropertyValue_TextChanged(object sender, TextChangedEventArgs e)
{
    (sender as TextBox).GetBindingExpression(TextBox.TextProperty).UpdateSource();

    this.ViewModel.UpdateFinalQuery();
}
0

精彩评论

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