我將一個ItemsControl綁定到名爲SwatchThumbnails的可觀察集合,該集合將包含數據以生成矩形。矩形可以有1-3個與之相關的顏色,並且在渲染時需要顯示多種顏色。我想我明白如何將一種顏色綁定到填充,但我需要一種方法來綁定多達三個,並讓它們均勻顯示。如何才能做到這一點?如何綁定多個顏色來填充WPF中的矩形?
這是我的XAML:
<ScrollViewer x:Name="sv_Thumbnails" Grid.ColumnSpan="2" Grid.Row="1" VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Auto">
<ItemsControl x:Name="ug_Thumbnails" ItemsSource="{Binding SwatchThumbnails, ElementName=mainWindow}">
<ItemsControl.ItemsPanel >
<ItemsPanelTemplate>
<UniformGrid Columns="6" RenderTransformOrigin="0,0.5" Cursor="Hand">
<Rectangle Width="50" Height="50" Fill="{Binding Color}" Margin="0 0 5 0" />
</UniformGrid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ScrollViewer>
我最初將通過C#代碼中的矩形進UniformGrid,所以我有一個用於分離出的顏色寫的原代碼。基本上,這是我用於生成矩形的原始代碼:
System.Windows.Shapes.Rectangle swatch = new System.Windows.Shapes.Rectangle();
swatch.Width = 50;
swatch.Height = 50;
swatch.Margin = new Thickness(0, 5, 5, 0);
swatch.StrokeThickness = 1;
swatch.Stroke = System.Windows.Media.Brushes.Gray;
swatch.Name = "s_" + _name.ToString();
double groupsize = 100/_colors.Count();
DrawingBrush blackBrush = new DrawingBrush();
DrawingGroup checkersDrawingGroup = new DrawingGroup();
List<SolidColorBrush> brushes = _colors;
double location = 0;
for (int i = 0; i < _colors.Count(); i++)
{
GeometryDrawing drawing = new GeometryDrawing(brushes[i], null,
new RectangleGeometry(new Rect(0, location, groupsize, groupsize)));
checkersDrawingGroup.Children.Add(drawing);
location += groupsize;
}
blackBrush.Drawing = checkersDrawingGroup;
swatch.Fill = blackBrush;
swatch.MouseUp += new MouseButtonEventHandler(loadSwatchResources);
最後,這裏是我可觀察的集合和色板縮略圖定義。
private ObservableCollection<SwatchThumbnail> swatchThumbnails = new ObservableCollection<SwatchThumbnail>();
public ObservableCollection<SwatchThumbnail> SwatchThumbnails
{
get { return swatchThumbnails; }
set { swatchThumbnails = value; }
}
public class SwatchThumbnail : INotifyPropertyChanged
{
public string name { get; set; }
public List<Color> colors { get; set; }
public bool selected { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
}
感謝您的支持,並對我的延遲表示歉意。我正在嘗試您的解決方案,但矩形行項目給我一個錯誤。 「屬性ItemsTemplate不支持」矩形「類型的值,這對我來說真的很奇怪, – Yecats 2014-11-09 17:36:56
@Yecats是的,這是我愚蠢的錯誤,請參閱更新的代碼 – 2014-11-09 17:40:21
感謝它讓我過去錯誤,但我遇到了麻煩我認爲,我已經確認observablecollection有三個項目,當我運行程序時,沒有顯示任何內容,轉換器上的斷點從來沒有觸發,這使我認爲綁定可能關閉了嗎? – Yecats 2014-11-09 17:57:15