Xamarin使用DataTrigger基于数据形成条件格式



我正在Xamarin Forms中开发一个聊天应用程序,并尝试添加条件格式,这取决于它是传入消息还是传出消息。

这是我的XAML:

<Frame 
Margin="1"
Padding="0"
x:Name="FrameRef"
x:DataType="model:ChatMessage">
<Frame 
CornerRadius="10"
Padding="7"
BackgroundColor="LightBlue"
HasShadow="false"
Margin="10,10,80,0">
<Frame.Triggers>
<DataTrigger
TargetType="Frame"
Binding="{Binding Source={x:Reference FrameRef}, Path=x:DataType.From}" Value="+1456456456">
<Setter Property="BackgroundColor" Value="Yellow"/>
</DataTrigger>
</Frame.Triggers>

当我使用Path="0"时;保证金";并且值="0";1〃;它是有效的。

我现在正试图使其在路径为x:DataType="的情况下工作;型号:ChatMessage";并检查"from"字段(指示消息是传入还是传出(。

我不确定数据触发器是否适合此应用程序,因为您实际上依赖于一种数据类型,而不是另一个字段的内容本身。来自文件:

DataTrigger类适用于检查其他控件上的值,以及添加到其中的控件上的任何属性。

您可能想要的是一个值转换器,它可以处理定位StaticResource并根据消息类型为您应用样式。此处提供完整的Microsoft文档。

在XAML元素上,您可以执行以下操作:

<Frame Style="{Binding foo, Converter={StaticResource FooToStyleConverter}}"/>

你的转换器会像这样工作:

public class FooToStyleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var someValue = (DataTye)value; // Convert 'object' to whatever type you are expecting
// evaluate the converted value
if (someValue.From != null && someValue.From == Enum.SomeoneElse)
return (Style)App.Current.Resources["StyleReceived"]; // return the desired style indicating the message is from someone else
return (Style)App.Current.Resources["StyleSent"]; // return a style indicating the message is from the sender
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// Usually unused, but inverse the above logic if needed
throw new NotImplementedException();
}
}

最后,将转换器设置为App.xaml中的静态资源(或页面上的本地资源(,这样您的页面就可以正确地引用它

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:DataBindingDemos">
<ContentPage.Resources>
<ResourceDictionary>
<local:FooToStyleConverter x:Key="FooToStyleConverter" />
....

最新更新