使用 MVVM 时,C# WPF 一个控件中有两个不同的 DataContext,并且第二个属性每次都是相同的
首先是代码:
<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
应该相同。但目前还行不通。 :(
First the code:
<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>
And the problem is that the property Data
on the OutputTextBox control comes from the list, but the property SelectedOutput
should come from the main DataContext the ViewModel. And the property SelectedOutput
should be the same for every entry in the list. But currently it dosn't work. :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的列表视图是否包含在标签中,如果是,网格是否具有来自 ViewModel 的 DataContext?如果是,它应该有效。
您在输出窗口中看到任何绑定错误吗?也许您应该尝试使用 Snoop 来查看 SelectedValue 的真实绑定。
编辑:请尝试除网格之外的类型,如果具有 ViewModel DataContext,则可能是 ListView。
does your listview is enclosed in tags and if yes does the grid has the DataContext from the ViewModel? if yes it should work.
do you see any binding errors in your output window? maybe you should try using Snoop to see your real binding of SelectedValue.
EDIT: Please try a Type other then Grid, maybe ListView if it has the ViewModel DataContext.