我有两个TextBox
,我希望第二个TextBox
的宽度为第一个TextBox
宽度的一半。
<TextBox x:Name="txtBox1" />
<TextBox x:Name="txtBox2" Width = "{Binding ElementName=txtBox1,Path=ActualWidth/2}"/>
答案 0 :(得分:4)
实现它的另一种方法。
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBox></TextBox>
<TextBox Grid.Column="1"></TextBox>
</Grid>
答案 1 :(得分:2)
不可能在xaml中使用算术动作,或者将其写入
后面的代码中txtBox2.Width = txtBox1.Width / 2;
或者创建一个转换器来执行此操作:
public class WidthToHalfConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (double)value / 2;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
XAML:
<Window.Resources>
<me:WidthToHalfConverter x:Key="converter" />
</Window.Resources>
...
<TextBox x:Name="txtBox2" Width = "{Binding ElementName=txtBox1,Path=ActualWidth, Converter={StaticResource converter}}"/>
答案 2 :(得分:1)
你必须为它创建转换器。您可以使用IValueConverter
获取更多详细信息,您可以使用提及的链接Click
答案 3 :(得分:1)
使用IValueConverter
存档此
public class MyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((double)value > 0)
{
return (double)value / 2;
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
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:w="clr-namespace:WpfApplication1"
Title="MainWindow"
Height="350"
Width="525">
<Window.Resources>
<w:MyConverter x:Key="MyConverter" />
</Window.Resources>
<Grid>
<StackPanel>
<TextBox Name="cmb1"
SelectionChanged="cmb1_SelectionChanged" />
<TextBox Name="cmb2"
Width="{Binding ElementName=cmb1, Converter={StaticResource MyConverter},Path=ActualWidth}" />
</StackPanel>
</Grid>