问题
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. :(
回答1:
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.
<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}}
}"
/>
来源:https://stackoverflow.com/questions/5960561/c-sharp-wpf-two-different-datacontext-in-one-control-while-using-mvvm-and-the-se