【发布时间】:2014-07-22 19:12:40
【问题描述】:
我建立了自己的“搜索面板”,其中有一个用于搜索词的文本框, 一个用于指定搜索条件的 ComboBox 和一个用于开始搜索的 Button。
ucSearchPanel XAML:
<UserControl x:Class="TestProjekt.Views.UserControls.ucSearchPanel"
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"
Width="auto" Height="auto">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Grid.Row="0" >
<Label Name="lblSearch" Width="{Binding ElementName=tbSearch, Path=ActualWidth}" HorizontalContentAlignment="Center">Suche</Label>
<Label Name="lblSearchCriteria" Width="{Binding ElementName=cbSearchCriteria, Path=ActualWidth}" HorizontalContentAlignment="{Binding ElementName=lblSearch, Path=HorizontalContentAlignment}">Suchkriterium</Label>
</StackPanel>
<StackPanel Orientation="Horizontal" Grid.Row="1">
<TextBox Name="tbSearch" MinWidth="100"></TextBox>
<ComboBox Name="cbSearchCriteria" MinWidth="{Binding ElementName=tbSearch, Path=MinWidth}" />
<Button Name="btnSearch">Suche</Button>
</StackPanel>
</Grid>
</UserControl>
但 ComboBox 中的搜索条件因用例而异... 因此,我想在不同的应用程序中使用 ucSearchPanel 中 ComboBox 中的 Property ItemsSource。
如果我为 ucSearchPanel 分配标识符 x: Name,我可以通过 Code-Behind 中的 C# 代码设置 ucSearchPanels.NameComboBox.ItemsSource。
但是,我也希望在 XAML 中这样做。因此,我创建了一个依赖属性:
using System.Collections;
using System.Windows;
using System.Windows.Controls;
ucSearchPanel.xaml.cs:
namespace TestProjekt.Views.UserControls
{
/// <summary>
/// Interaktionslogik für ucSearchRegion.xaml
/// </summary>
public partial class ucSearchPanel : UserControl
{
public static readonly DependencyProperty cbSearchCriteriaItemsSourceProperty;
public IEnumerable cbSearchCriteriaItemsSource
{
get { return (IEnumerable)GetValue(cbSearchCriteriaItemsSourceProperty); }
set { SetValue(cbSearchCriteriaItemsSourceProperty, value) }
}
public string cbDisplayMemberPath
{
get
{
return cbSearchCriteria.DisplayMemberPath;
}
set
{
cbSearchCriteria.DisplayMemberPath = value;
}
}
static ucSearchPanel()
{
cbSearchCriteriaItemsSourceProperty = DependencyProperty.Register("cbSearchCriteriaItemsSource",
typeof(IEnumerable), typeof(ucSearchPanel));
}
public ucSearchPanel()
{
InitializeComponent();
}
}
}
正如您在源代码中看到的,我没有直接将 Dependency 属性分配给 ComboBox.ItemsSource。 因此,如果我将 ObservableCollection 绑定到属性,则在 ucSearchPanel 的 ComboBox 中不会显示任何项目。
我想知道在 C# 代码中如何以及在何处指定公共静态只读 DependencyProperty cbSearchCriteriaItemsSourceProperty 引用 cbSearchCriteria.ItemsSource。
我要提前感谢您的帮助并留下来
致以最诚挚的问候
【问题讨论】:
-
您可以在
DependencyProperty.Register()指定委托 -
您好 Henk,感谢您的回答。但我不知道你是什么意思。 pkease,你能给我举个例子吗?