[英]WPF UserControl - SelectedItem of a Usercontrol DataGrid to bind to a ItemSource to DataGrid outside the UserControl
嗨,我的WPF UserControl知識就像一個小時。 所以請原諒我,如果有關於這個問題的SO有很多教程或/和答案(說實話我不認為這可以做,需要重新編寫代碼...因此我想我問的原因)
因此,在創建UserControl之前,我有一個數據網格,可以根據用戶在文本框中鍵入的文本來篩選客戶。 找到后,該過濾器DataGrid的SelectedItem將用於綁定到包含新集合的新DataGrid。
所以....
過濾DataGrid XAML
SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"
ItemsSource="{Binding Source={StaticResource cvsCustomers}}"
用戶在該網格中選擇客戶后,
新的DataGrid將包含基於SelectedCustomer的屬性行
ItemsSource="{Binding SelectedCustomer.CustomerOrders}"
一切都很好,很有效。
但是,我將在我的項目中大量使用此過濾器客戶結果功能,因此我創建了一個UserControl,其中過濾器DataGrid正在運行。
我已將此UserControl放在視圖中,因此問題是我需要將Usercontrol中的selectedItem綁定到視圖中的DataGrid。 (如上所述)
所以我在View中的DataGrid中需要這樣的東西。
ItemsSource="{Binding ElementName=myUserControl, Path=SelectedCustomer.CustomerOrders}"
好一點啰嗦但我希望你能理解這個問題,而且我已經掌握了足夠的知識。 如果我做錯了,請告訴我,然后向下投票。
干杯
您可以向自定義用戶控件添加新的依賴項屬性,並將數據網格項源綁定到該屬性。 確保在用戶控件的數據網格上處理選擇已更改事件,並將依賴項屬性設置為所選項。
public object MySelectedItem
{
get { return (object)GetValue(MySelectedItemProperty); }
set { SetValue(MySelectedItemProperty, value); }
}
// Using a DependencyProperty as the backing store for MySelectedItem. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MySelectedItemProperty =
DependencyProperty.Register("MySelectedItem", typeof(object), typeof(YOURUSERCONTROLTYPE), new UIPropertyMetadata(null));
處理選擇更改事件
public YourUserControl()
{
InitializeComponent();
dgv.SelectionChanged += dgv_SelectionChanged;
}
void dgv_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MySelectedItem = dgv.SelectedItem;
}
然后綁定到
ItemsSource="{Binding ElementName=myUserControl, Path=MySelectedItem.CustomerOrders}"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.