Ponieważ TextBlock.Background nie współpracuje z kolekcjami, tylko pojedynczymi wartościami.
public partial class MainWindow : Window
{
public static readonly DependencyProperty RectBackgroundProperty = DependencyProperty.Register(
"RectBackground",
typeof( Brush ),
typeof( MainWindow ),
new UIPropertyMetadata( new SolidColorBrush( Colors.Black ) )
);
public Brush RectBackground
{
get { return (Brush)GetValue( RectBackgroundProperty ); }
set { SetValue( RectBackgroundProperty, value ); }
}
public ObservableCollection<Color> Goods { get; private set; }
public MainWindow()
{
Goods = new ObservableCollection<Color>();
Goods.CollectionChanged += new NotifyCollectionChangedEventHandler( Goods_CollectionChanged );
InitializeComponent();
}
void Goods_CollectionChanged( object sender, NotifyCollectionChangedEventArgs e )
{
if( Goods.Count > 2 )
{
RectBackground = new SolidColorBrush( Goods[2] );
}
else
{
RectBackground = new SolidColorBrush( Colors.Black );
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Goods.Add(Colors.Blue);
Goods.Add(Colors.Cornsilk);
}
}
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Name="myw">
<Grid>
<TextBox Background="{Binding Path=RectBackground, ElementName=myw}" Height="100" Width="100" Margin="64,51,339,160">adasdassdadadas</TextBox>
<Button Height="100" Margin="186,130,80,81" Click="Button_Click" >After two clicks background sholud change</Button>
</Grid>
</Window>