1 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
這是一個(gè)工作示例。
假設(shè)您的用戶控件有兩個(gè)控件;一個(gè)ComboBox和一個(gè)Button。您希望能夠?qū)⒅骺丶ǜ缚丶┲械哪承﹥?nèi)容綁定到用戶控件。然后,在選擇某些內(nèi)容并單擊按鈕后,您希望用戶控件將事件發(fā)生通知給父級(jí),并傳遞所選值。
用戶控件XAML:
<UserControl ...
d:DesignHeight="40" d:DesignWidth="200">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="40"/>
</Grid.ColumnDefinitions>
<ComboBox Grid.Column="0" Margin="4" Name="ItemsComboBox"
ItemsSource="{Binding Source, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
<Button Grid.Column="1" Margin="4" Content="+"
Click="Button_Click"/>
</Grid>
</UserControl>
以下綁定將允許您將數(shù)據(jù)列表綁定到組合框(形成父級(jí)):
ItemsSource="{Binding Source, RelativeSource={RelativeSource AncestorType=UserControl}}"
在您的 中MainWindow,您將像這樣使用該控件:
<Grid>
<local:UCComboButton Grid.Row="0" Width="200" Height="40" x:Name="MyUC"
Source="{Binding Names}"/>
</Grid>
并在UserControl后面的s代碼中:
public partial class UCComboButton : UserControl
{
public UCComboButton()
{
InitializeComponent();
}
// We use this dependency property to bind a list to the combo box.
public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(IEnumerable), typeof(UCComboButton), new PropertyMetadata(null));
public IEnumerable Source
{
get { return (IEnumerable)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
// This is to send the occurred event, in this case button click, to the parent, along with the selected data.
public class SelectedItemEventArgs : EventArgs
{
public string SelectedChoice { get; set; }
}
public event EventHandler<SelectedItemEventArgs> ItemHasBeenSelected;
private void Button_Click(object sender, RoutedEventArgs e)
{
var selected = ItemsComboBox.SelectedValue;
ItemHasBeenSelected?.Invoke(this, new SelectedItemEventArgs { SelectedChoice = selected.ToString() });
}
}
現(xiàn)在在MainWindow.xaml.cs:
public MainWindow()
{
InitializeComponent();
// Subscribe to the item selected event
MyUC.ItemHasBeenSelected += UCButtonClicked;
Names = new List<string>
{
"A",
"B",
"C"
};
DataContext = this;
}
void UCButtonClicked(object sender, UCComboButton.SelectedItemEventArgs e)
{
var value = e.SelectedChoice;
// Do something with the value
}
請(qǐng)注意,上面的Names列表是從主窗口綁定到用戶控件的內(nèi)容XAML。
- 1 回答
- 0 關(guān)注
- 119 瀏覽
添加回答
舉報(bào)