我创建了一个 UserControl (MediaList),其中包含一个绑定到属性“ToolsBar”的 ItemControl。这个想法是允许从 MediaList 控件外部添加自定义按钮/控件。
我的问题是我正在尝试在工具栏中添加一个按钮,该按钮与 UserControl 本身绑定。我不会将 MediaList (UserControl) 的 DataContext 覆盖为“this”,因为我需要使用在根窗口中定义的 DataModel。
也许我这样做的方式完全错误?
这是使用 MediaList 的自定义按钮的窗口示例:
<localControls:MediaList x:Name="NewMediaList">
<localControls:MediaList.ToolsBar>
<Button Content="{StaticResource ResourceKey=MoveToPlaylist}"
IsEnabled="{Binding ElementName=NewMediaList, Path=SelectedMedia, Converter={localConverters:ObjectToBool}}"/>
</localControls:MediaList.ToolsBar>
</localControls:MediaList>
到目前为止,我尝试了多种绑定但没有成功,例如:
- {Binding ElementName=MediaListControl, Path=SelectedMedia, Converter={localConverters:ObjectToBool}}"
- {绑定RelativeSource={x:静态RelativeSource.Self},Path=SelectedMedia,Converter={localConverters:Debug}}
- {绑定 SelectedMedia,RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type UserControl}}}
- {绑定 SelectedMedia,RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type localControls:MediaList}}}
请注意,我将它们从记忆中写回,并且我还尝试将 MediaList.xaml 中的 ItemControl 和 StackPanel(包含 ItemControm)的 DataContext 设置为 MediaList 对象本身。
媒体列表.xaml:
<UserControl x:Class="MediaPlaylist.Controls.MediaList"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:localConverters="clr-namespace:Suisse.MediaPlaylist.Converters"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
x:Name="MediaListControl">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<DataGrid Grid.Row="0"
AutoGenerateColumns="False"
ItemsSource="{Binding ElementName=MediaListControl, Path=Playlist.Medias}"
SelectedItem="{Binding ElementName=MediaListControl, Path=SelectedMedia, Mode=TwoWay}">
<DataGrid.Columns>
<DataGridTextColumn Header="Title"
Binding="{Binding Title}"
IsReadOnly="True"/>
<DataGridTextColumn Header="File"
Binding="{Binding FilePath}"
IsReadOnly="True"/>
</DataGrid.Columns>
</DataGrid>
<StackPanel Orientation="Horizontal"
HorizontalAlignment="Right"
Grid.Row="1">
<ItemsControl ItemsSource="{Binding ElementName=MediaListControl, Path=ToolsBar}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
<Separator Visibility="{Binding ElementName=MediaListControl, Path=ToolsBar.Count, Converter={localConverters:ObjectToVisibility}}" />
<Button
HorizontalAlignment="Right"
Content="Delete"
Click="OnDelete_Click"
IsEnabled="{Binding ElementName=MediaListControl, Path=SelectedMedia, Converter={localConverters:ObjectToBool}}"/>
</StackPanel>
</Grid>
谢谢