UWP通过绑定更改TextBox的前景色

时间:2019-04-14 08:11:40

标签: uwp

我有此代码:

   <TextBox TextWrapping="Wrap" Text="{Binding Date}"
                                       />

我也想通过Binding更改此TextBox颜色。

我尝试了以下操作:

  public class ArticleItem
    {
        public string Title { get; set; }
        public string Date { get; set; }
        public string Url { get; set; }
        public SolidColorBrush ColorBrush;
    }

并尝试绑定ColorBrush,但是前景色不会改变。

                    list.Items.Add(new ArticleItem() { Title = item.Title.Text, Date = item.PublishedDate.ToString(), ColorBrush = new SolidColorBrush(Colors.Red), Url = item.Links[0].Uri.ToString()});

在XML中:

<TextBox TextWrapping="Wrap" Text="{Binding Date}" Foreground="{Binding ColorBrush}"
                                       />

1 个答案:

答案 0 :(得分:0)

绑定是绑定到属性,而不是字段。您需要将ColorBrush定义为属性。

public class ArticleItem
{
    public string Title { get; set; }
    public string Date { get; set; }
    public string Url { get; set; }
    public SolidColorBrush ColorBrush { get; set; }
}
public sealed partial class MainPage : Page
{
    public ObservableCollection<ArticleItem> list { get; set; }

    public MainPage()
    {
        this.InitializeComponent();
        list = new ObservableCollection<ArticleItem>();
        list.Add(new ArticleItem() { Title = "title1", ColorBrush = new SolidColorBrush(Colors.Red), Date = DateTime.Now.ToString() });
        list.Add(new ArticleItem() { Title = "title2", ColorBrush = new SolidColorBrush(Colors.Blue), Date = DateTime.Now.ToString() });
        this.DataContext = this;
    }
}
<ListView ItemsSource="{Binding list}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextBox Text="{Binding Date}" Foreground="{Binding ColorBrush}"></TextBox>
            </DataTemplate>
        </ListView.ItemTemplate>
</ListView>