【问题标题】:C# WPF two different DataContext in One Control while using MVVM and the secound property is every time the sameC#WPF在一个控件中使用MVVM时有两个不同的DataContext,并且第二个属性每次都相同
【发布时间】:2011-05-11 07:14:03
【问题描述】:

首先是代码:

<ListView ItemsSource="{Binding DataTransferModel.Output}" Background="Transparent" Margin="0" VerticalContentAlignment="Top" AlternationCount="2" Name="lvOutput" ScrollViewer.VerticalScrollBarVisibility="Auto" Grid.Row="2">
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Margin="0,1">
                <UserControls:OutputTextBox Text="{Binding Data, Mode=OneWay}" 
                                            IsReadOnly="True" 
                                            Grid.Row="2" 
                                            TextWrapping="WrapWithOverflow" 
                                            SelectedValue="{Binding Path=DataContext.SelectedOutput, 
                                                            Mode=TwoWay, 
                                                            UpdateSourceTrigger=PropertyChanged, 
                                                            RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}
                                                            }" 
                                            />
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

问题是OutputTextBox控件上的属性Data来自列表,但属性SelectedOutput应该来自ViewModel的主DataContext。对于列表中的每个条目,属性SelectedOutput 应该相同。但目前它不起作用。 :(

【问题讨论】:

    标签: wpf binding datacontext relativesource


    【解决方案1】:

    您的列表视图是否包含在标签中,如果是,网格是否具有来自 ViewModel 的 DataContext?如果是的话,它应该工作。

    您是否在输出窗口中看到任何绑定错误?也许您应该尝试使用Snoop 来查看您对 SelectedValue 的真实绑定。

    编辑:请尝试除 Grid 之外的其他类型,如果有 ViewModel DataContext,则可能是 ListView。

    <UserControls:OutputTextBox Text="{Binding Data, Mode=OneWay}" 
                                            IsReadOnly="True" 
                                            Grid.Row="2" 
                                            TextWrapping="WrapWithOverflow" 
                                            SelectedValue="{Binding Path=DataContext.SelectedOutput, 
                                                            Mode=TwoWay, 
                                                            UpdateSourceTrigger=PropertyChanged, 
                                                            RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}
                                                            }" 
                                            />
    

    【讨论】:

    • 外部范围的下一个标记是列表中的网格,并且 DataContext 在 Window 的 Loaded 事件上设置为 ViewModel。但它不起作用。 :(
    • 请尝试 Snoop 看看 SelectedValue 的实际绑定是什么。
    猜你喜欢
    • 2010-12-21
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 2012-12-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    相关资源
    最近更新 更多