XAML:
<TextBlock Name="resultado" HorizontalAlignment="Center"
Height="152" Margin="14,324,23,0" TextWrapping="Wrap"
VerticalAlignment="Top" Width="419" TextAlignment="Center"
FontSize="100" Foreground="{Binding Color}"/>
我需要做什么才能在我的C#代码中添加Foreground
属性中的Color?
正在使用这种方法:
SolidColorBrush bb = new SolidColorBrush();
答案 0 :(得分:0)
这是一个使用ViewModel的工作解决方案,允许您通过更改ListBox选择来更改TextBox颜色。
这是.xaml代码:
<Grid>
<StackPanel>
<TextBlock Foreground="{Binding color}" Text="This is a test." FontSize="50" HorizontalAlignment="Center"/>
<ListBox SelectionChanged="ListBox_SelectionChanged" Name="ForegroundChooser">
<ListBoxItem Content="Green"/>
<ListBoxItem Content="Blue"/>
<ListBoxItem Content="Red"/>
</ListBox>
</StackPanel>
</Grid>
这是初始化和ListBox代码隐藏:
public partial class MainWindow : Window
{
VM data = new VM();
public MainWindow()
{
InitializeComponent();
ForegroundChooser.SelectedIndex = 0;
this.DataContext = data;
}
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ForegroundChooser.SelectedIndex == 0) data.color = new SolidColorBrush(Colors.Green);
if (ForegroundChooser.SelectedIndex == 1) data.color = new SolidColorBrush(Colors.Blue);
if (ForegroundChooser.SelectedIndex == 2) data.color = new SolidColorBrush(Colors.Red);
}
}
这是您的ViewModel类:
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace WpfApplication1
{
class VM : INotifyPropertyChanged
{
private SolidColorBrush _color;
public SolidColorBrush color
{
get { return _color; }
set
{
if (_color == value)
return;
else _color = value;
OnPropertyChanged("color");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
您需要做的是创建ViewModel类的实例并将.xaml DataContext
设置为它。创建要绑定到的值的私有实例(例如_color
),然后使用color
创建该值的公共方法(在本例中为get
),并可选择{ {1}}方法。绑定到公共实例(set
)。在Foreground="{Binding color}"
中,您需要调用set
来通知绑定值已更改。