我有一个userControl,其中包含一个文本块和一个文本框,但是我一直试图通过DependencyProperties将参数传递给它。
这是一些东西:
userControl XAML:
<UserControl x:Class="WpfApp1.Controls.InfoField"
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:WpfApp1.Controls"
mc:Ignorable="d"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<DockPanel>
<TextBlock Text="{Binding TextInBlock}" HorizontalAlignment="Right" Margin="2" Width="160"></TextBlock>
<TextBox Text="{Binding BindingInBox}" Grid.Column="1" Width="200" Margin="2"></TextBox>
</DockPanel>
</Grid>
</UserControl>
后面的相关代码:
using System.Windows;
using System.Windows.Controls;
namespace WpfApp1.Controls
{
/// <summary>
/// Logique d'interaction pour InfoField.xaml
/// </summary>
public partial class InfoField : UserControl
{
public static readonly DependencyProperty TextInBlockProperty =
DependencyProperty.Register("TextInBlock", typeof(string), typeof(TextBlock));
public static readonly DependencyProperty BindingInBoxProperty =
DependencyProperty.Register("BindingInBox", typeof(string), typeof(TextBox));
public string TextInBlock
{
get => (string) GetValue(TextInBlockProperty);
set => SetValue(TextInBlockProperty, value);
}
public string BindingInBox
{
get => (string)GetValue(BindingInBoxProperty);
set => SetValue(BindingInBoxProperty, value);
}
public InfoField()
{
InitializeComponent();
this.DataContext = this;
}
}
}
和MainWindow XAML:
<Grid ColumnSpan="4" Row="1" Name="detailsGrid"
DataContext="{Binding ElementName=listBoxBooks,Path=SelectedItem}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
------> <controls:InfoField Grid.ColumnSpan="2" BindingInBox="{Binding Author,ElementName=mainWindow}" TextInBlock="Auteur :"></controls:InfoField>
<Button Grid.Row="0" Grid.Column="2" Click="ButtonBase_OnClick">Click me!</Button>
<TextBlock Text="Titre :" HorizontalAlignment="Right" Grid.Row="1"></TextBlock>
<TextBox Text="{Binding Title}" Grid.Column="1" Grid.Row="1" Width="200"></TextBox>
</Grid>
目前,Visual Studio在我放置文本箭头的行上给我一个错误;错误显示:“'TextInBlock'属性已由'TextBlock'注册”。我不明白此错误消息。 请注意,这两个绑定之间有区别,一个绑定引用另一个字段(也通过绑定,该字段为“作者”),而另一个绑定只是一个简单的字符串。
谢谢。