Привязка ширины столбцов к DependencyProperty с помощью IValueConverter - PullRequest
0 голосов
/ 30 января 2012

Я пытаюсь сделать ширину столбца в переменной элемента Grid. Для этого у меня есть DependencyProperty "ItemWidth" и я связываю элемент Width от Button с этим DP. Из-за TwoWay-Binding мне нужен конвертер, который преобразует двойные в DataGridLength.

Мой MainWindow.xaml выглядит так:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:utils="clr-namespace:WpfApplication1" Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.Resources>
        <utils:ColumnWidthConverter x:Key="columnWidthConverter"/>
    </Grid.Resources>
    <Button Grid.Row="0" Grid.Column="0" Width="{Binding Path=ItemWidth, Mode=TwoWay, Converter={StaticResource columnWidthConverter}}" Click="Shorter_Click">shorter</Button>
    <Button Grid.Row="0" Grid.Column="1" Width="{Binding Path=ItemWidth, Mode=TwoWay, Converter={StaticResource columnWidthConverter}}" Click="Longer_Click">longer</Button>
</Grid>
</Window>

ColumnWidthConverter.cs выглядит следующим образом:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows;

namespace WpfApplication1
{
    class ColumnWidthConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
                return null;
            else
            {
                DataGridLengthConverter cv = new DataGridLengthConverter();
                object result = cv.ConvertFrom(value);
                return result;
            }

        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
                return null;
            else
            {
                DataGridLengthConverter cv = new DataGridLengthConverter();
                return cv.ConvertTo(value, typeof(double));
            }
        }
    }
}

И MainWindow.xaml.cs выглядит так:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public double ItemWidth
        {
            get { return (double)GetValue(ItemWidthProperty); }
            set { SetValue(ItemWidthProperty, value); }
        }

        public static readonly DependencyProperty ItemWidthProperty =
        DependencyProperty.Register("ItemWidth", typeof(double), typeof(MainWindow), new UIPropertyMetadata(0.0));

        private void Shorter_Click(object sender, RoutedEventArgs e)
        {
            this.ItemWidth -= 100;
        }

        private void Longer_Click(object sender, RoutedEventArgs e)
        {
            this.ItemWidth += 100;
        }
    }
}

Таким образом, ширина кнопок должна измениться, когда я нажму одну из кнопок. Но этого не происходит. Можете ли вы сказать мне, почему это и какое-то решение?

Ответы [ 2 ]

1 голос
/ 30 января 2012

я использую следующее для моего GridSplitter

public class DoubleToGridLengthConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {

        double i = (double)value;

        GridLength result = new GridLength(i);

        return result;

    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {

        GridLength g = (GridLength)value;

        return (double)g.Value;

    }

}

XAML

Width="{Binding Source={x:Static Properties:Settings.Default}, Path=GridSplitter, Mode=TwoWay, Converter={StaticResource GridLengthConverter}}"
1 голос
/ 30 января 2012

Вы не указываете источник в привязке, следовательно, он относится к DataContext, который, по-видимому, нигде не установлен, если вы добавите его, который должен работать.Например,

<Window DataContext="{Binding RelativeSource={RelativeSource Self}}" ...

Возможно, вы захотите (т.е. вы определенно должны ) изучить отладку привязок данных , если вы не знакомы с ней.

Вы также связываете свойства, которые не нужны для конвертера, ведь конвертер, вероятно, вызовет проблемы здесь, вы не хотели связывать ColumnDefinition.Width?

...