我有一个带有数据模板的列表视图,如下所示:
<ListView x:Name="errorListBox" Width="615" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollMode="Enabled" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Background="White" Grid.Row="1" ItemsSource="{x:Bind Errors}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock TextAlignment="Left" Foreground="Red" TextWrapping="Wrap" Text="{Binding}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
我想为其中的不同TextBlock设置不同的颜色。当前前景设置为“红色”。
如何在uwp c ++中将前景颜色与某些属性绑定?
可接受的答案后面的工作c ++代码。这对某人可能会有帮助:
public ref class Error sealed
{
private:
Platform::String^ m_error;
Windows::UI::Xaml::Media::SolidColorBrush^ m_foreGround;
public:
Error(Platform::String^ error, Windows::UI::Xaml::Media::SolidColorBrush^ colorBrush)
{
m_error = error;
m_foreGround = colorBrush;
}
property Platform::String^ ErrorText
{
Platform::String^ get()
{
return m_error;
}
void set(Platform::String^ val)
{
m_error = val;
}
}
property Windows::UI::Xaml::Media::SolidColorBrush^ Foreground
{
Windows::UI::Xaml::Media::SolidColorBrush^ get()
{
return m_foreGround;
}
void set(Windows::UI::Xaml::Media::SolidColorBrush^ brush)
{
m_foreGround = brush;
}
}
};
答案 0 :(得分:0)
您需要将一个集合绑定到您的列表视图,并且该集合中的每个项目都将具有一个 SolidColorBrush 属性,该属性将用于绑定到您的文本块的前景。
c#代码
public sealed partial class MainPage : Page
{
ObservbleCollection<Error> Errors = new ObservableCollection<Error>();
public MainPage()
{
this.InitializeComponent();
Errors.Add(new Error("errorText1",new SolidColorBrush(Colors.Blue)));
Errors.Add(new Error("errorText2",new SolidColorBrush(Colors.Red)));
// keep adding errors to the errors collection.
}
}
class Error
{
public Error(string errorText, SolidColorBrush foreground)
{
ErrorText = error;
Foreground = foreground;
}
public string ErrorText { get; set; }
public SolidColorBrush Foreground { get; set; }
}
Xaml
<ListView x:Name="errorListBox" Width="615" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollMode="Enabled" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Background="White" Grid.Row="1" ItemsSource="{x:Bind Errors}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="Error">
<StackPanel Orientation="Vertical">
<TextBlock TextAlignment="Left" Foreground="{x:Bind Foreground}" TextWrapping="Wrap" Text="{x:Bind ErrorText}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>