WPF MultiBinding

FredGrit發表於2024-06-09
//xaml
<Window x:Class="WpfApp149.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp149"
        mc:Ignorable="d" WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <local:RGBConverter x:Key="rgbConverter"/>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" FontSize="18" VerticalAlignment="Center" HorizontalAlignment="Center">
            <TextBlock.Text>
                <MultiBinding StringFormat="R:{0:N0},G:{1:N0},B:{2:N0}">
                    <Binding Path="Value" ElementName="redSlider"/>
                    <Binding Path="Value" ElementName="greenSlider"/>
                    <Binding Path="Value" ElementName="blueSlider"/>
                </MultiBinding>
            </TextBlock.Text>
        </TextBlock>
        <Rectangle Grid.Row="1" Stroke="Black" StrokeThickness="3" Margin="4">
            <Rectangle.Fill>
                <MultiBinding Converter="{StaticResource rgbConverter}">
                    <Binding Path="Value" ElementName="redSlider"/>
                    <Binding Path="Value" ElementName="greenSlider"/>
                    <Binding Path="Value" ElementName="blueSlider"/>
                </MultiBinding>
            </Rectangle.Fill>
        </Rectangle>
        <Slider Minimum="0" Maximum="255" Margin="4" x:Name="redSlider" Grid.Row="2"/>
        <Slider Minimum="0" Maximum="255" Margin="4" x:Name="greenSlider" Grid.Row="3"/>
        <Slider Minimum="0" Maximum="255" Margin="4" x:Name="blueSlider" Grid.Row="4"/>
    </Grid>
</Window>

//converter
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media;

namespace WpfApp149
{
    internal class RGBConverter : IMultiValueConverter
    {
        SolidColorBrush brush = new SolidColorBrush();
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            brush.Color = Color.FromRgb(System.Convert.ToByte(values[0]), System.Convert.ToByte(values[1]),
                System.Convert.ToByte(values[2]));
            return brush;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

相關文章