0

好的,我在 Silverlight MVVM Light 应用程序中有以下 XAML 标记。这是观点的一部分。在视图代码隐藏中的 btnClearBodyMark 的单击事件中,我尝试使用 .Parent 属性向上遍历树,第一个父级是水平堆栈面板,然后它的父级是垂直堆栈面板,它的父级是网格,但是网格的父级是另一个网格??如何获得对按钮所属的 ListBoxItem 的引用???

<ListBox Name="listboxBodyMarkValues" ItemsSource="{Binding}" Height="Auto" Width="Auto" SelectionChanged="listboxBodyMarkValues_SelectionChanged">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <StackPanel x:Name="stackBodyMarkList" Orientation="Vertical" Margin="5" Height="Auto">
                    <StackPanel Orientation="Horizontal" Margin="5" Height="Auto">
                        <TextBlock x:Name="txtId" Width="50" Height="Auto" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Center" FontWeight="Bold" Text="{Binding Id}" />
                        <ComboBox x:Name="comboDom1" Width="100" Margin="5" HorizontalAlignment="Left" VerticalAlignment="Center" ItemsSource="{Binding Dom1}" SelectedItem="{Binding Dom1SelectedItem, Mode=TwoWay}" Visibility="{Binding ComboIsVisible}"/>
                        <Button x:Name="btnClearBodyMark" Content="Delete Body Mark" Margin="5" HorizontalAlignment="Left" VerticalAlignment="Center" Click="btnClearBodyMark_Click" />                                         
                    </StackPanel>
                    <TextBox x:Name="txtNotes" VerticalAlignment="Stretch" VerticalContentAlignment="Top" HorizontalAlignment="Stretch" TextWrapping="Wrap" Text="{Binding ManualText, Mode=TwoWay}" AcceptsReturn="True" Margin="5" MaxWidth="400" MaxHeight="200" VerticalScrollBarVisibility="Auto" IsEnabled="{Binding ManualTextIsEnabled}" />
                </StackPanel>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
4

2 回答 2

0

通常,在 MVVM 中,如果您绑定Command,您可以传递一个CommandParameter并将DataContext放入其中,但最重要的事情是传递“ DataContext ”。由于这与 Click 事件相关联,因此将发送者类型转换为按钮,访问 DataContext,这应该是列表框中的对象。因此,如果您的列表框绑定到“客户”的ItemsSource ,则按钮上的“ DataContext ”应该是“客户”对象。它应该被传递,因为 StackPanel 的 DataContext 将是该对象,并且它的所有子对象都应该具有相同的对象。例如:

public void btnClearBodyMark_Click(object sender, ButtonClickEventArgs e)
{
    var myRef = (sender as Button).DataContext;
}

类似的东西。
PS,因为这很可能绑定到一组“对象”。该项目不再是每个说的 ListBoxItem,而是绑定集合的数据类型。此外,如果您将 ListBox 的SelectedItem属性绑定到 ViewModel 中的属性,并且模式为Mode=TwoWay
,您可以节省“SelectionChanged”事件的工作。确保您的属性(例如 ViewModel 中的“SelectedListItem”)通过确保您的 ViewModel 实现我认为在 System.ComponentModel 中找到的 INotifyPropertyChanged 来通知属性更改事件。这样,一旦用户选择了某些东西,就不需要偶数处理程序;)。

于 2012-04-29T23:34:34.473 回答
0

我也为此苦苦挣扎。作为旁注:您不应该传递 ListBoxItem。视图模型不应该关心列表是如何实现的。

真正帮助我的是 MVVM-Light 工具包。您可以创建自己的命令来接受一个参数(ListBoxItem 的 DataContext 的类型),然后在您想要的事件上执行它。

详情在这里:http ://www.galasoft.ch/mvvm/#tutorials

于 2012-04-29T23:52:46.103 回答