在xaml中更改绑定值
本文关键字:绑定 xaml | 更新日期: 2023-09-27 18:01:22
我想知道是否有一种方法可以将一个元素的属性绑定到另一个元素,但修改两者之间的数据。例如,我可以有一个文本块的字体大小绑定到窗口的宽度/20或类似的东西?我已经遇到了一些地方,这将是有用的几次,但总能找到解决方案(通常涉及到添加字段到我的viewModel)。最好是完全的xaml解决方案。
是的,通过实现IValueConverter。
您的场景看起来像这样的转换器:
[ValueConversion(typeof(double), typeof(double))]
public class DivideBy20Converter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var f = (double) value;
return f/20.0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var f = (double)value;
return f * 20.0;
}
}
…在XAML中:
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfApplication3="clr-namespace:WpfApplication3"
Title="MainWindow" Height="350" Width="525"
x:Name="Window">
<Window.Resources>
<wpfApplication3:DivideBy20Converter x:Key="converter"></wpfApplication3:DivideBy20Converter>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBox FontSize="{Binding ElementName=Window, Path=Width, Converter={StaticResource converter}}"></TextBox>
</Grid>
</Window>
您可以使用IValueConverters
来处理这样的逻辑。
Converte
r将宽度除以ConverterParameter
中提供的值。public class MyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null && parameter != null)
{
double divisor = 0.0;
double _val = 0.0;
if (double.TryParse(value.ToString(), out _val) && double.TryParse(parameter.ToString(), out divisor))
{
return _val / divisor;
}
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
Xaml: <Window x:Class="WpfApplication7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converters="clr-namespace:WpfApplication7"
Title="MainWindow" Height="124" Width="464" Name="YourWindow" >
<Window.Resources>
<converters:MyConverter x:Key="MyConverter" />
</Window.Resources>
<StackPanel>
<TextBlock FontSize="{Binding ElementName=YourWindow, Path=ActualWidth, Converter={StaticResource MyConverter}, ConverterParameter=20}" />
</StackPanel>
</Window>