У меня есть составной элемент управления из двух частей - метки и значения.Я определил свойство зависимости под названием «ValueAlignment», которое должно устанавливать горизонтальное выравнивание текста в части значения элемента управления.Независимо от того, что я делаю, выравнивание по умолчанию влево.Вот два примера:
![enter image description here](https://i.stack.imgur.com/4GxjC.png)
![enter image description here](https://i.stack.imgur.com/dPhI1.png)
Как видите, я определил несколько пользовательских свойств зависимостей, таких как LabelWidth и ValueWidth.Они работают хорошо, но не выравнивание.Свойства зависимостей определены для объекта OmniBox следующим образом:
public static readonly DependencyProperty ValueAlignmentProperty = DependencyProperty.Register("ValueAlignment", typeof(HorizontalAlignment), typeof(OmniBox), new FrameworkPropertyMetadata(HorizontalAlignment.Stretch));
public static readonly DependencyProperty LabelWidthProperty = DependencyProperty.Register("LabelWidth", typeof(String), typeof(OmniBox), new FrameworkPropertyMetadata((String)"40*"));
public static readonly DependencyProperty ValueWidthProperty = DependencyProperty.Register("ValueWidth", typeof(String), typeof(OmniBox), new FrameworkPropertyMetadata((String)"60*"));
etc...
public HorizontalAlignment ValueAlignment
{
get { return (HorizontalAlignment)GetValue(ValueAlignmentProperty); }
set { SetValue(ValueAlignmentProperty, value); }
}
Обратите внимание, что тип HorizontalContentAlignment имеет тип HorizontalAlignment
, определенный MSDN .В xaml моего элемента управления у меня есть предопределенный набор шаблонов, которые соответствуют различным типам элементов управления для отображения связанных данных, и они относятся к набору общих предопределенных стилей.Вот все, что относится к элементу управления «Ограниченная нагрузка» выше:
<ControlTemplate TargetType="{x:Type local:OmniBox}" x:Key="OBTextBoxTemplate">
<Grid x:Name="PART_Grid" Style="{StaticResource GridStyle}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding Path=LabelWidth, RelativeSource={RelativeSource TemplatedParent}}"/>
<ColumnDefinition Width="{Binding Path=ValueWidth, RelativeSource={RelativeSource TemplatedParent}}"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label x:Name="PART_Label" Style="{StaticResource LabelStyle}" />
<TextBox x:Name="PART_Value" Style="{StaticResource TextBoxStyle}"/>
</Grid>
</ControlTemplate>
<Style x:Key="GridStyle" TargetType="Grid" BasedOn="{StaticResource BaseElement}">
<Setter Property="Focusable" Value="False" />
</Style>
<Style x:Key="TextBoxStyle" TargetType="TextBox" BasedOn="{StaticResource BaseValueStyle}">
<Setter Property="Margin" Value="{StaticResource BoxedValueMargin}" />
<Setter Property="Padding" Value="{StaticResource BoxedValuePadding}" />
<Setter Property="Text" Value="{Binding Path=Value, RelativeSource={RelativeSource TemplatedParent}}" />
<Setter Property="IsReadOnly" Value="{Binding Path=ReadOnly, RelativeSource={RelativeSource TemplatedParent}}" />
<Setter Property="HorizontalContentAlignment" Value="{Binding Path=ValueAlignment, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:OmniBox}}}" />
</Style>
<Style x:Key="BaseStyle" TargetType="Control" BasedOn="{StaticResource BaseElement}">
<Setter Property="Padding" Value="0" />
<Setter Property="MinWidth" Value="50" />
<Setter Property="VerticalContentAlignment" Value="Top" />
</Style>
<Style x:Key="BaseElement" TargetType="FrameworkElement">
<Setter Property="Margin" Value="0" />
<Setter Property="MinHeight" Value="15" />
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="VerticalAlignment" Value="Top" />
</Style>
Как видите, резина встречается с дорогой, когда я пытаюсь связать HorizontalContentAlignment стилизованного текстового поля со свойством зависимостей OmniBox.ValueAlignment:
<Setter Property="HorizontalContentAlignment" Value="{Binding Path=ValueAlignment, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:OmniBox}}}" />
Я также пробовал более простую версию:
<Setter Property="HorizontalContentAlignment" Value="{Binding Path=ValueAlignment, RelativeSource={RelativeSource TemplatedParent}}" />
, но ни одна из них не работает.Обратите внимание, что для других элементов в шаблоне элемента управления используется привязка к пользовательскому свойству TemplatedParent, например, к ширине столбцов в шаблоне элемента управления и свойству Text в стиле TextBox, но пока они работают, горизонтальное выравнивание содержимого не выполняется.Кто-нибудь может увидеть, что я пропустил, и это не сработало?