正如標題所示,我是
我的 MainWindow.xaml 有 MainWindowViewModel.cs 作為它的 DataContext,在這個 ViewModel 中有一個 ObservableCollection。
在 .xaml 檔案中,我添加了一個 ListBox,如下所示:
<ListBox ItemsSource="{Binding RoleTypes}">
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton Content="{Binding}"
GroupName="ClientRole"
Command="{Binding SetSelectedRoleCommand, Mode=OneWay}"
CommandParameter="{Binding Content,
RelativeSource={RelativeSource Self}}">
</RadioButton>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
問題是我需要將我的 Content 變數系結到我的 Observable 集合的值,但我還需要系結到我的命令,該命令可從 Window.DataContext 訪問。嘗試將我的命令系結到 Window.DataContext 將起作用,但現在,內容將系結到 ViewModel 類本身。
有沒有一種方法可以讓我的單選按鈕系結到 ObservableCollection 的內容,同時能夠使用正確的引數呼叫我的命令?
非常感謝!
uj5u.com熱心網友回復:
您可以將命令系結到DataContext
使用RelativeSource
<ListBox ItemsSource="{Binding RoleTypes}">
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton Content="{Binding}"
GroupName="ClientRole"
Command="{Binding DataContext.SetSelectedRoleCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}"
CommandParameter="{Binding}">
</RadioButton>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
或者您可以將名稱設定為ListBox
或視窗本身并使用以下方式系結ElementName
:
<ListBox x:Name="list" ItemsSource="{Binding RoleTypes}">
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton Content="{Binding}"
GroupName="ClientRole"
Command="{Binding DataContext.SetSelectedRoleCommand, ElementName=list}"
CommandParameter="{Binding}">
</RadioButton>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
順便說一句,你為什么需要這么復雜的系結CommandParameter
?似乎應該是簡單{Binding}
的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/508258.html