2012-01-05 77 views
1

我有一個wpf,mvvm應用程序,使用catel(http://catel.codeplex.com)framework \ toolkit,C#.Net 4.0。該應用程序有一個帶有TextBlock和ComboBox的ListBox。 ListBox和ComboBox從ViewModel的2個不同的ObservableCollection中填充。我需要保存(到數據庫),當用戶點擊一個按鈕時,用戶從ComboBox中選擇一個項目的列表框中的每一行。 SelectionChanged事件不會觸發列表框中的任何組合框。這個想法是我在ViewModel中添加了一個列表(ArrayList或IList?),每次用戶選擇一個ComboBox中的一個項目以及該項目被選中的行。ListBox中的組合框不會觸發SelectionChanged事件

或者我想通過嘗試使用ComboBoxe SelectionChanged事件來解決這個問題?我也嘗試迭代ListBox.Items,但這看起來像一個hak,如果可能的話,我想避免ViewModel中的UI元素邏輯。

的XAML:

<Grid> 
<StackPanel Orientation="Horizontal"> 
    <Label Width="180">Field1</Label> 
    <ListBox Height="200" 
      IsSynchronizedWithCurrentItem="True" 
      ItemsSource="{Binding List1, Mode=OneWay}" 
      Name="listBox1" 
      SelectionMode="Single" 
      Width="300"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <StackPanel Orientation="Horizontal" Width="290"> 
        <TextBlock Width="90" Text="{Binding}"></TextBlock> 
         <ComboBox Width="180" ItemsSource="{Binding DataContext.List2, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}" DisplayMemberPath="Field1"> 
          <i:Interaction.Triggers> 
           <i:EventTrigger EventName="SelectionChanged"> 
            <catel:EventToCommand Command="{Binding SelectionChangedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" DisableAssociatedObjectOnCannotExecute="False" PassEventArgsToCommand="True" /> 
           </i:EventTrigger> 
          </i:Interaction.Triggers> 
         </ComboBox> 
        </StackPanel> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 
</StackPanel> 

視圖模型代碼:

//in the ViewModel constructor 

SelectionChangedCommand = new Command<SelectionChangedEventArgs>(OnSelectionChangedCommandExecute, OnSelectionChangedCommandCanExecute); 



public Command<SelectionChangedEventArgs> SelectionChangedCommand { get; private set; } 

private bool OnSelectionChangedCommandCanExecute() 
{ 
    return true; 
} 

private void OnSelectionChangedCommandExecute(SelectionChangedEventArgs e) 
{ 
    // add or update list.... 
} 

回答

3

在命令結合您使用的結合具有相對源綁定...

考慮將這些綁定變化

1)使用列表框作爲Ancestortype

2)雖然綁定使用Path = DataContext.SelectionChangedCommand,否則它將採用列表框作爲datacontext。

<catel:EventToCommand Command="{Binding Path=DataContext.SelectionChangedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}" DisableAssociatedObjectOnCannotExecute="False" PassEventArgsToCommand="True" /> 
+0

Dangit我不好Bathineni由於某種原因,我的眼睛看不到,這是一個WPF應用程序..抱歉..我的錯誤 – MethodMan 2012-01-05 18:06:19

+0

這讓我一半。事件觸發,這給我從ComboBox(e.AddedItems [0] .ToString();)中選定的項目,但不是已更改的行。更改組合框選擇不會選中\突出顯示列表框中的行。我會繼續嘗試,如果我知道我會發布我的解決方案。謝謝。 – user657527 2012-01-05 18:23:11

+0

@ user657527我可以知道你爲什麼傳遞'EventArgument'嗎? – Ankesh 2012-01-06 10:23:05

相關問題