我有一个窗口,其中有一个矩形。我希望它的填充是另一个矩形填充的渐变停止,但在不同的窗口。 “源”窗口定义为:
<Window x:Class="WPF1.ColorSelectorWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:WPF1"
x:Name="colorSelectorWindow"
Title="ColorSelectorWindow" Height="281" Width="540">
有一个矩形
<Rectangle HorizontalAlignment="Left" Margin="40,120,0,41" Stroke="Black" Width="100" Name="ColorPicker">
<Rectangle.Fill>
<SolidColorBrush>
<SolidColorBrush.Color>
...
</SolidColorBrush.Color>
</SolidColorBrush>
</Rectangle.Fill>
</Rectangle>
和财产:
public partial class ColorSelectorWindow : Window
{
public Brush SelectedBrush
{
get
{
return ColorPicker.Fill;
}
}
}
现在,在目标窗口中,我定义了一个矩形:
<Rectangle Height="213" HorizontalAlignment="Left" Margin="27,8,0,0" Name="rectangle1" VerticalAlignment="Top" Width="25" Grid.Row="1">
<Rectangle.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
<GradientStop Offset="0" Color="Blue" />
<GradientStop Offset="1" Color="{Binding ElementName=colorWindowSelector, Path=SelectedBrush, Converter={StaticResource BrushToColorConverter}}" />
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
其中BrushToColorConverter将Brush转换为Color。这不起作用,我不知道为什么,似乎我有一个问题,解决那个“源”窗口..我正在目标窗口构造函数中构建它:
public MainWindow()
{
colorWindow = new ColorSelectorWindow();
colorWindow.Name = "colorWindowSelector";
colorWindow.Hide();
InitializeComponent();
}
我只是隐藏并展示它,而不是肯定地关闭。如何正确绑定它?
答案 0 :(得分:1)
你需要在你的MainWindow上有属性暴露的SelectedBrush,你只需要使用RelativeSource绑定到这个Brush的颜色。所以,这将为你做到 -
<Rectangle Height="213" HorizontalAlignment="Left" Margin="27,8,0,0" Name="rectangle1" VerticalAlignment="Top" Width="25" Grid.Row="1">
<Rectangle.Fill>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
<GradientStop Offset="0" Color="Blue" />
<GradientStop Offset="1" Color="{Binding Path=Owner.SelectedBrush, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType =Window} Converter={StaticResource BrushToColorConverter}}" />
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
但请确保在创建窗口时,将其所有者设置为MainWindow -
public MainWindow()
{
InitializeComponent();
colorWindow = new ColorSelectorWindow();
colorWindow.Name = "colorWindowSelector";
colorWindow.Owner = this;
colorWindow.Hide();
}