【发布时间】:2015-05-21 06:24:34
【问题描述】:
我正在尝试构建一个简单的颜色选择器作为 WPF 用户控件,但我无法将所选颜色返回到主窗口。
我的主窗口 XAML 如下所示:
<Window x:Class="ColorPicker.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:view="clr-namespace:ColorPicker"
Title="TestWindow" SizeToContent="WidthAndHeight">
<StackPanel Orientation="Horizontal">
<Rectangle Fill="{Binding MyColor}" Margin="10,10,10,10" Width="100" Height="300"/>
<view:WPFColorPicker SelectedColor="{Binding MyColor, Mode=TwoWay}" Width="200" Height="300"/>
</StackPanel>
</Window>
以及视图模型和代码隐藏:
namespace ColorPicker
{
public class TestViewModel
{
public TestViewModel()
{
MyColor = new SolidColorBrush(Color.FromRgb(255, 0, 0));
}
public Brush MyColor { get; set; }
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new TestViewModel();
}
}
}
WPFColorPicker 用户控件 XAML 是:
<UserControl x:Class="ColorPicker.WPFColorPicker"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel>
<Rectangle x:Name="rtlfill" Fill="{Binding SelectedColor}" HorizontalAlignment="Stretch" Height="60" Margin="10,10,10,10" Stroke="Black" VerticalAlignment="Top"/>
<ListBox HorizontalAlignment="Stretch" SelectedValue="{Binding SelectedColor}" VerticalAlignment="Stretch" Margin="0,0,0,81" ScrollViewer.HorizontalScrollBarVisibility="Disabled" x:Name="colorList">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Rectangle Fill="{Binding .}" Margin="0,0,0,5" Width="20" Height="20" Stroke="#FF211E1E" OpacityMask="Black" StrokeThickness="1" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</UserControl>
和代码隐藏:
namespace ColorPicker
{
public partial class WPFColorPicker : UserControl
{
List<Brush> brushList;
public WPFColorPicker()
{
InitializeComponent();
brushList = new List<Brush>() {
new SolidColorBrush(Color.FromRgb(255, 0, 0)),
new SolidColorBrush(Color.FromRgb( 0,255, 0)),
new SolidColorBrush(Color.FromRgb( 0, 0,255))};
this.colorList.ItemsSource = brushList;
DataContext = this;
}
public static readonly DependencyProperty SelectedColorProperty = DependencyProperty.Register("SelectedColor",
typeof(Brush),
typeof(WPFColorPicker),
new FrameworkPropertyMetadata(new SolidColorBrush(Colors.Red),
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public Brush SelectedColor
{
get { return (Brush)GetValue(SelectedColorProperty); }
set { SetValue(SelectedColorProperty, value); }
}
}
}
所以,我遇到的问题是 SelectedColor 上的绑定(使用来自 TestViewModel 的 MyColor)不起作用。
通过查看有关 StackOverflow 和各种教程的其他问题,我认为 UserControl 设置正确以将 SelectedColor 绑定为 TwoWay DependencyProperty,但它不起作用。
谁能给我一些见解?
【问题讨论】:
标签: c# wpf xaml user-controls