Muhammad Nauman
Muhammad Nauman

Reputation: 213

Half to the width of the Textbox

I have two TextBox's and i want to make the second TextBox's width to be half of the first TextBox's width.

<TextBox x:Name="txtBox1" />

<TextBox x:Name="txtBox2" Width = "{Binding ElementName=txtBox1,Path=ActualWidth/2}"/>

Upvotes: 0

Views: 421

Answers (4)

Nitin Purohit
Nitin Purohit

Reputation: 18580

One more way of achieving it.

   <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="2*"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <TextBox></TextBox>
        <TextBox Grid.Column="1"></TextBox>
    </Grid>

Upvotes: 4

Vimal CK
Vimal CK

Reputation: 3563

Use IValueConverter to archive this

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>

Upvotes: 1

Tzah Mama
Tzah Mama

Reputation: 1567

It is impossible to use arithmetic actions in xaml either write it in code behind

txtBox2.Width = txtBox1.Width / 2;

Or create a converter to do so:

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}}"/>

Upvotes: 2

Dhaval Patel
Dhaval Patel

Reputation: 7601

you have to create convertor for it. you can use IValueConverter for more details you can use mentioned link Click

Upvotes: 1

Related Questions