Включение привязки объектов в параметр команды MultiBinding - PullRequest
0 голосов
/ 09 апреля 2011

Я пытаюсь использовать <MultiBinding> для передачи двух параметров в команду моего ViewModel, но у меня возникают проблемы с получением синтаксического анализатора XAML для принятия моих попыток.

Рассмотрим следующий ListView, содержащийся в моем UserControl, который связан с коллекцией Ticket объектов.

<ListView x:Name="lvTicketSummaries" 
                  ItemsSource="{Binding TicketSummaries}"  
                  ItemContainerStyle="{DynamicResource ResourceKey=ListViewItem}"
                  IsSynchronizedWithCurrentItem="True">

Соответствующий стиль ListViewItem

<Style x:Key="ListViewItem" TargetType="{x:Type ListViewItem}">
    <Setter Property="ContextMenu" Value="{DynamicResource ResourceKey=cmListViewItem}"/>
    <!-- A load of irrelevant stuff ->
</Style>

И элемент ContextMenu, на который ссылается источник моего запроса;

<!-- ContextMenu DataContext bound to UserControls view model so it can access 'Agents' ObservableCollection -->    
<ContextMenu x:Key="cmListViewItem" DataContext="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext}">
    <MenuItem Header="Send as Notification" ItemsSource="{Binding Path=Agents}">
        <MenuItem.ItemContainerStyle>
            <Style TargetType="{x:Type MenuItem}">
                <!-- Display the name of the agent (this works) -->
                <Setter Property="Header" Value="{Binding Path=Name}"/>
                <!-- Set the command to that of one on usercontrols viewmodel (this works) -->
                <Setter Property="Command" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}, Path=DataContext.SendTicketNotification}" />
                <Setter Property="CommandParameter">
                    <Setter.Value>
                        <MultiBinding Converter="{StaticResource ResourceKey=TicketNotificationParameterConverter}">
                            <MultiBinding.Bindings>
                                <!-- This SHOULD be the Agent object I clicked on to trigger the Command. This does NOT work, results in either exception or 'UnsetValue' -->
                                <Binding Source="{Binding}" />
                                <!-- Also pass in the Ticket item that was clicked on to open the context menu, this works fine -->
                                <Binding RelativeSource="{RelativeSource AncestorType={x:Type ListView}}" Path="SelectedItem" />
                            </MultiBinding.Bindings>
                        </MultiBinding>
                    </Setter.Value>
                </Setter>
            </Style>
        </MenuItem.ItemContainerStyle>
    </MenuItem>
</ContextMenu>

Итак, вот что я пытаюсь сделать;

  • В контекстном меню есть один пункт «Отправить заявку как уведомление», в котором при выборе перечисляются все доступные Agents, которые могут получать указанное уведомление. Это работает.

  • Когда я нажимаю на одну из этих опций агента, я хочу, чтобы элемент контекстного меню отправлял элемент ticket, который был выбран из listview, чтобы показать контекстное меню (это работает), И Agent пункт, который я выбрал из контекстного меню. Я наполовину достиг этого с помощью MultiBinding

    <MultiBinding Converter="{StaticResource ResourceKey=TicketNotificationParameterConverter}">
                            <MultiBinding.Bindings>
                                <!-- This works, it sends the Ticket object to the Converter -->
                                <Binding RelativeSource="{RelativeSource AncestorType={x:Type ListView}}" Path="SelectedItem" />
                                <!-- This caused an exception saying that I can only set 'Path' property on DependencyProperty types -->
                                <Binding Path="{Binding}" />
                            </MultiBinding.Bindings>
                        </MultiBinding>
    

Теперь, хотя фактическая настройка контекстного меню кажется мне несколько сложной. Фактическое указание на то, что один из параметров MultiBinding должен быть фактическим элементом, привязанным к нажатому ContextMenu.MenuItem, представляется довольно простой командой. Контекстное меню правильно перечисляет всех агентов, и поэтому я бы подумал, что просто запросить текущий объект для отправки в качестве параметра команды, просто. Я также пытался;

<Binding RelativeSource={RelativeSource AncestorType={x:Type MenuItem}} Path="SelectedItem" />

а также

<Binding RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}} Path="SelectedItem" />

Но все, что отправляется в преобразователь параметров, это UnsetValue

Спасибо за ваше время и любые ваши предложения.

1 Ответ

3 голосов
/ 04 мая 2011

Эта строка нечетна:

<Binding Path="{Binding}" />

Является ли текущий DataContext строкой, которая была бы достаточной в качестве пути, который нашел бы что-то в текущем DataContext, который на самом деле не является строкой в конце концов? Имеет смысл.

Вы имели в виду сделать это вместо того, чтобы связать с DataContext?

<Binding />
...