使用 XAML 绑定依赖项属性



在我的用户控件 MainControl 中,我有一个名为 repository 的依赖属性。我想使用 xaml 在主窗口中绑定此存储库属性

<my:MainControl x:Name="mainControl" Repository="{Binding }" Visibility="Visible" />

在 MainWindow.xaml 中.cs我有

public MainWindow()
{
InitializeComponent();
_repository = new CarRepository();
DataContext = _repository;
}

在 MainControl 构造函数中,我正在考虑使用

public MainControl()
{
InitializeComponent();
lblCountCars.Content = string.Format("there is {0} cars.", Repository.CountAllCars());
}

我在这里做错了什么吗Repository="{Binding }"?当我在代码后面注册用户控件时,一切都没问题,但我想学习如何使用 xaml 执行此操作。

更新以使其清晰。我有MainWindow它使用两个用户控件。MainControlTreassureControl. 我想将类型为ICarRepository的存储库发送到任何此控件,因此我在MainControlTreassureControl中创建了名为RepositoryICarRepository类型的 DependencyProperty。

我的目标是将存储库实例发送到MainControlRepository属性 (DP) 并在标签上打印内容属性lblCountCars.Content = Repository.CountAllCars();

我还希望用户控制中的这个存储库实例进一步工作,而不仅仅是显示简单的文本。

所以我尝试了下面的建议

MainWindow.xaml

<my:MainControl x:Name="mainControl" Repository="{Binding Repository}" />

MainWindow.xaml.cs

private ICarRepository _repository;   
public MainWindow()
{
InitializeComponent();
_repository = new CarRepository(); 
DataContext = _repository;
}

MainControl.xaml

<UserControl x:Name="mainControl">
<Label Name="lblCountBooks" Content="{Binding ElementName=mainControl, Path=Repository.CountAllBooks()}" 
<ItemsControl ItemsSource="{Binding ElementName=mainControl, Path=Repository}" />

MainControl.xaml.cs

public static readonly DependencyProperty RepositoryProperty = DependencyProperty.Register(
"Repository",
typeof(ICarRepository),
typeof(MainControl),
new PropertyMetadata(null));
public ICarRepository Repository
{
get { return (ICarRepository)GetValue(RepositoryProperty); }
set { SetValue(RepositoryProperty, value); }
}

标签内容未使用预期内容进行更新。

在用户控件中使用依赖项属性时,我使用元素名绑定绑定到 DP。 所以我会删除你的

lblCountCars.Content = string.格式("有{0}辆汽车。 Repository.CountAllCars());

并做这样的事情:

<UserControl x:Name="uc">
...      
<Label Content="{Binding ElementName=uc, Path=Repository.Count}"/><!-- you can use ContentStringFormat here to get you formattet string-->
<ItemsControl ItemsSource="{Binding ElementName=uc, Path=Reportsitory}"/>

主窗口中的绑定看起来正确。

编辑: 您可以只绑定到属性。所以你需要一个属性,而不是 Repository.CountAllBooks()。如果您没有机会在 ICarRepository 上创建属性,则可以使用转换器和存储库属性作为转换参数来获取您的信息。

这可能是您的 MainControls 数据上下文未在构造函数中设置。您需要使用 DataContextChanged 事件 (http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.datacontextchanged(v=vs.110).aspx)。

例如:

public MainControl()
{
InitializeComponent();
DataContextChanged += MainControl_DataContextChanged;
}
void MainControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
lblCountCars.Content = string.Format("there is {0} cars.", Repository.CountAllCars());    
}

最新更新