MainWindow.xaml:
<Window.Resources>
<local:ViewModel x:Key="vm"/>
<local:MyMultiValueConverter x:Key="MyMultiValueConverter"/>
</Window.Resources>
<StackPanel DataContext="{StaticResource vm}">
<DataGrid Name="dg" ItemsSource="{Binding View}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Col1" Binding="{Binding SomeString}" MinWidth="30" MaxWidth="300" >
<DataGridTextColumn.Width>
<MultiBinding Converter="{StaticResource MyMultiValueConverter}">
<Binding Path="WidthValue" Source="{StaticResource vm}"/>
<Binding Path="WidthDefault" Source="{StaticResource vm}"/>
</MultiBinding>
</DataGridTextColumn.Width>
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="TextAlignment" Value="Center"/>
<Setter Property="Width">
<Setter.Value>
<MultiBinding Converter="{StaticResource MyMultiValueConverter}">
<Binding Path="WidthValue" Source="{StaticResource vm}"/>
<Binding Path="WidthDefault" Source="{StaticResource vm}"/>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
<CheckBox IsChecked="{Binding WidthDefault}" Content="Default Width"/>
<Slider Width="200" Height="20" Minimum="5" Maximum="300" Value="{Binding WidthValue}"/>
<!--<TextBox Text="{Binding WidthValue}"/>-->
</StackPanel>
MainWindow.xaml.cs:
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
ObservableCollection<Data> col = new ObservableCollection<Data>();
col.Add(new Data() { SomeString = 44 });
col.Add(new Data() { SomeString = 84 });
col.Add(new Data() { SomeString = 104 });
cvs.Source = col;
}
private CollectionViewSource cvs = new CollectionViewSource();
public ICollectionView View { get => cvs.View; }
private double _widthValue = 30;
public double WidthValue
{
get => this._widthValue;
set { this._widthValue = value; OnPorpertyChanged(); }
}
private bool _widthDefault = false;
public bool WidthDefault
{
get => this._widthDefault;
set { this._widthDefault = value; OnPorpertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
internal void OnPorpertyChanged([CallerMemberName] string propName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
public class Data
{
public double SomeString { get; set; }
}
public class MyMultiValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
double w =30;
if (!(bool)values[1]) double.TryParse(values[0].ToString(), out w);
return w;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
The result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread.