【发布时间】:2021-09-16 21:56:27
【问题描述】:
我正在编写一个聊天客户端,我的消息显示在一个列表框中。在 xaml 中,我的列表框设置如下:
<ListBox x:Name="list_chat" Background="{x:Null}" VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch" Margin="256,0,0,64" BorderThickness="0" BorderBrush="{x:Null}" Foreground="White" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.CanContentScroll="False" Focusable="False" Grid.ColumnSpan="2">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Background="#bd93f9" Margin="64,0,8,0" HorizontalAlignment="Right">
<TextBlock Text="{Binding}" TextWrapping="Wrap" LineStackingStrategy="MaxHeight" Foreground="White" HorizontalAlignment="Right" VerticalAlignment="Stretch" Margin="16,8,32,0" LineHeight="Auto" TextTrimming="None" TextAlignment="Right" Width="Auto" Padding="0" UseLayoutRounding="True">
</TextBlock>
<Button HorizontalAlignment="Right" VerticalAlignment="Center" Width="32" Height="32" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="White" Margin="0">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border
x:Name="border"
Background="{x:Null}"
BorderBrush="{x:Null}"
BorderThickness="0"
CornerRadius="90"
TextBlock.Foreground="White">
<Grid>
<Image
x:Name="buttonImage"
Source="C:\Users\janke\source\repos\Unichat\Unichat\bin\Debug\pictures\icons\reply-line.png" Width="16" Height="16"
/>
<ContentPresenter
Margin="{TemplateBinding Padding}"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter TargetName="border" Property="Background" Value="{x:Null}" />
<Setter TargetName="border" Property="BorderBrush" Value="{x:Null}" />
<Setter TargetName="buttonImage" Property="Source" Value="C:\Users\janke\source\repos\Unichat\Unichat\bin\Debug\pictures\icons\reply-fill.png" />
</Trigger>
<Trigger Property="IsPressed" Value="true">
<Setter TargetName="border" Property="Background" Value="{x:Null}" />
<Setter TargetName="border" Property="BorderBrush" Value="{x:Null}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
</Button>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我想通过绑定来控制我的网格属性的“HorizontalAlignment”,以便消息向右或向左对齐,具体取决于消息是发送还是接收。尽管我知道这是可能的,但我没有在互联网上找到这样做的方法。我只是还不明白绑定。
我的 C# 代码如下所示:
list_chat.Items.Add(textRange.Text);
提前致谢!
【问题讨论】:
-
您可以只使用数据触发器。我会有一个代表每条消息的视图模型。那将有一个字符串文本属性 bool 发起者。然后样式具有默认的左对齐,并且 datatrigger 对原始值 false 应用右。
标签: c# wpf data-binding binding listbox