Это два разных перечислений:
TextAlignment перечислений:http://msdn.microsoft.com/en-us/library/system.windows.textalignment(v=vs.110).aspx
HorizontalAlignment Перечень:http://msdn.microsoft.com/en-us/library/system.windows.horizontalalignment(v=vs.110).aspx
Хотя TextAlignment
содержит Center
, Justify
, Left
и Right
, HorizontalAlignment
содержит Center
, Left
, Right
и Stretch
. Итак, как вы видите, они не то же самое.
Создайте конвертер, если хотите использовать его на основе другого.
Вот очень простой конвертер (настроить по своему вкусу):
public class HorizontalToTextAlignmentConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
TextAlignment textAlignment;
// All I'm doing here is simply getting the integer value of the Enumeration.
switch ((int)value)
{
case 0:
// Left to Left
textAlignment = TextAlignment.Left;
break;
case 1:
// Center to Center
textAlignment = TextAlignment.Center;
break;
case 2:
// Right to Right
textAlignment = TextAlignment.Right;
break;
default:
// Stretch to Justify
textAlignment = TextAlignment.Justify;
break;
}
return textAlignment;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
HorizontalAlignment horizontalAlignment;
// All I'm doing here is simply getting the integer value of the Enumeration.
switch ((int)value)
{
case 0:
// Left to Left
horizontalAlignment = HorizontalAlignment.Left;
break;
case 1:
// Right to Right
horizontalAlignment = HorizontalAlignment.Right;
break;
case 2:
// Center to Center
horizontalAlignment = HorizontalAlignment.Center;
break;
default:
// Justify to Stretch
horizontalAlignment = HorizontalAlignment.Stretch;
break;
}
return horizontalAlignment;
}
}
XAML
тестового код:
<Window.Resources>
<local:HorizontalToTextAlignmentConverter x:Key="h2tAlignmentConverter"/>
</Window.Resources>
<Grid>
<ListBox>
<ListBoxItem HorizontalAlignment="Right">
<TextBlock TextWrapping="Wrap" Text="Some text"
TextAlignment="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=HorizontalAlignment, Converter={StaticResource h2tAlignmentConverter}}"
Width="400"/>
</ListBoxItem>
</ListBox>
</Grid>
MSDN
порядка этих нумераций было немного, поэтому я просто ушел в кода, чтобы выяснить их. Вот их код для справки:
public enum TextAlignment
{
Left = 0,
Right = 1,
Center = 2,
Justify = 3,
}
public enum HorizontalAlignment
{
Left = 0,
Center = 1,
Right = 2,
Stretch = 3,
}
EDIT:
Я немного подумал о своем последнем комментарии, и я думаю, что вы не можете видеть изменения выравнивания текста из-за самой не TextBlock
выравнивание в пределах родителя ListBoxItem
. Итак, в качестве одного из возможных сценариев, если ListBoxItem
больше, чем TextBlock
, вы не увидите правильных изменений.Вы можете выполнить синхронизацию их выравниваний путем привязки HorizontalContentAlignment
от ListBoxItem
к собственным HorizontalAlignment
.
Вот XAML
:
<Grid>
<ListBox>
<ListBoxItem HorizontalAlignment="Left" BorderThickness="1" BorderBrush="Red"
Width="400" HorizontalContentAlignment="{Binding RelativeSource={RelativeSource Self}, Path=HorizontalAlignment}">
<TextBlock TextWrapping="Wrap" Text="Some text" Background="Green" Foreground="White"
TextAlignment="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=HorizontalAlignment, Converter={StaticResource h2tAlignmentConverter}}"
Width="300"/>
</ListBoxItem>
</ListBox>
</Grid>
Вот визуальное представление различных мировоззрений. ListBoxItem
является Red
, TextBlock
является Green
и ListBox
занимает Grid
& Window
.
Left
выравнивания:
Right
выравнивания:
Center
выравнивания:
Stretch
выравнивание (текст Justified
):
Лучшая часть является то, что HorizontalContentAlignment
просто HorizontalAlignment
, поэтому не требуется никакого преобразования.
прежде всего 'TextAlignment' &' HorizontalAlignment' - это два разных перечисления, поэтому они могут быть несовместимы друг с другом. но вы можете попробовать, добавив в режим привязки 'Mode = TwoWay'. – pushpraj
Спасибо за быстрый ответ! Я пробовал это, но это не сработало. Есть ли способ конвертировать из HorizontalAligment в TextAlignment? – user3952846