我想做这个
从此视图模型
public class MainWindowViewModel : ViewModelBase
{
public ObservableCollection<TextRun> RunList { get; set; }
public MainWindowViewModel()
{
RunList = new ObservableCollection<TextRun>(new List<TextRun>
{
new TextRun("th", "Red"),
new TextRun("is", "Green"),
new TextRun(" a", "Blue"),
new TextRun(" T", "Yellow"),
new TextRun("es", "Black"),
new TextRun("t!", "Orange"),
new TextRun("!!", "Violet")
});
}
}
public class TextRun
{
public string Text { get; set; }
public string Color { get; set; }
public TextRun(string title, string color)
{
Text = title;
Color = color;
}
}
您也可以考虑公开一个抽象模型
文本、字体等(即视图模型)并创建实际的内联
通过 DataTemplate 的对象。没有代码,只有axaml即
。遗憾的是,链接的答案并未扩展这种做事方式,我需要详细信息。在过去的两天里,我尝试了不同的组合,但我几乎要开始撞墙了。但原则上它应该很容易。例如,如果文本位于不同行,则这将是 axaml:
<ItemsControl ItemsSource="{Binding RunList}" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Text}" Foreground="{Binding Color}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
但是我需要不同颜色的文本位于同一行。
我知道我一定在使用跑步。这个静态 axaml 确实做到了这一点:
<TextBlock>
<Run Text="Th" Foreground="Red"/><Run Text="is" Foreground="Green"/><Run Text=" a" Foreground="Blue"/><Run Text=" t" Foreground="Yellow"/><Run Text="es" Foreground="Black"/><Run Text="t!" Foreground="Orange"/><Run Text="!!" Foreground="Violet"/>
</TextBlock>
但我需要它是“模型视图绑定”(动态),正如摘录所建议的那样。
我前天刚开始玩Avalonia,所以在这里摸索,请多多包涵。到目前为止,感觉很直观。这是我遇到的第一个减速带。
包含WPF标签,因为WPF的xaml解决这个问题应该与Avalonia的axaml非常相似。遗憾的是,我也没有 WPF 经验。
<ItemsControl ItemsSource="{Binding RunList}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Text}" Foreground="{Binding Color}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>