我正在尝试使用 ComboBox 创建一个 UserControl,并绑定到 ItemSource 和 SelectedItem(我在 UserControl 中还有一些其他具有绑定功能的控件,但这些控件工作正常,已被删除以简化下面的代码)。< /p>
ItemSource 绑定似乎正在工作,并且 ComboBox 填充了 MainWindow 中指定的列表,但 SelectedItem 不会在任一方向发生变化时更新。尽管 VersionText 在 UserControl 之外的 SelectedSoftwareVersion.Version 更改时更新。
我可能在这里遗漏了一些基本的东西,但我看不到它。我对 UserControls 的经验有限。
SoftwareTile.xaml
<UserControl x:Class="MyApp.Controls.SoftwareTile"
x:Name="softwareTile"
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:local="clr-namespace:MyApp.Controls"
mc:Ignorable="d"
d:DesignHeight="100" d:DesignWidth="150">
<Grid DataContext="{Binding RelativeSource={RelativeSource AncestorLevel=1, AncestorType={x:Type UserControl}, Mode=FindAncestor}}">
<StackPanel>
<TextBlock x:Name="VersionText"
Text="{Binding ElementName=softwareTile, Path=Version}"/>
<TextBlock x:Name="VersionLabel"
Text="Version"/>
<ComboBox x:Name="VersionSelect"
ItemsSource="{Binding ElementName=softwareTile, Path=VersionList}"
SelectedItem="{Binding ElementName=softwareTile, Path=VersionSelected}"/>
</StackPanel>
</Grid>
</UserControl>
SoftwareTile.cs
using System.Windows;
using System.Windows.Controls;
using System.Collections;
namespace MyApp.Controls
{
public partial class SoftwareTile : UserControl
{
public static readonly DependencyProperty VersionProperty = DependencyProperty.Register("Version", typeof(string), typeof(SoftwareTile), new PropertyMetadata(string.Empty));
public static readonly DependencyProperty VersionListProperty = DependencyProperty.Register("VersionList", typeof(IEnumerable), typeof(SoftwareTile), new UIPropertyMetadata(null));
public static readonly DependencyProperty VersionSelectedProperty = DependencyProperty.Register("VersionSelected", typeof(object), typeof(SoftwareTile), new UIPropertyMetadata(null));
public string Version
{
get { return (string)GetValue(VersionProperty); }
set { SetValue(VersionProperty, value); }
}
public IEnumerable VersionList
{
get { return (IEnumerable)GetValue(VersionListProperty); }
set { SetValue(VersionListProperty, value); }
}
public object VersionSelected
{
get { return (object)GetValue(VersionSelectedProperty); }
set { SetValue(VersionSelectedProperty, value); }
}
}
}
主窗口.xaml
<uc:SoftwareTile x:Name="ST1"
Version="{Binding SelectedSoftwareVersion.Version}"
VersionList="{Binding SoftwareVersions.VersionList}"
VersionSelected="{Binding SelectedSoftwareVersion.Version, Mode=TwoWay}" />