从 ColumnDefinition Width XAML WPF 绑定 TextBox 宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15743501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:24:48  来源:igfitidea点击:

Bind TextBox Width from ColumnDefinition Width XAML WPF

wpfxamlbindingtextboxwidth

提问by soufiane labdai

In my WPF project i want to bind TextBox Width property from ColumnDefinition Width. Now, it's not working !

在我的 WPF 项目中,我想从 ColumnDefinition Width 绑定 TextBox Width 属性。现在,它不起作用!

I used a converter (GridLengthConverter) to convert data to width.

我使用转换器 (GridLengthConverter) 将数据转换为宽度。

This is my code :

这是我的代码:

<TextBox Grid.Column="1" Grid.Row="1" Style="{StaticResource SearchWhite}"  Name="tbSearch"
Visibility="{Binding RelativeSource={RelativeSource AncestorType={x:Type mic:DataGrid}},
Path=ShowSearchBoxes, Converter={StaticResource visibleConverter}}" Width="{Binding
RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ColumnDefinition}},
Path=Width, Converter={StaticResource gridLengthConverter}, Mode=TwoWay}"/>

gridLengthConverter is GridLengthConverter from assembly : PresentationFramework.

gridLengthConverter 是来自 assembly 的 GridLengthConverter:PresentationFramework。

I get an error "Unable to convert data attribut 'Converter'..." (translation from french).

我收到错误消息“无法转换数据属性 'Converter'...”(法语翻译)。

Someone can helps ?

有人可以帮忙吗?

回答by Grenkin

<Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Name="col1" Width="200"/>
            <ColumnDefinition />
        </Grid.ColumnDefinitions>

        <TextBox Width="{Binding ElementName=col1, Path=Width}" 
                 Grid.Column="0" Height="20"/>
</Grid>

回答by ctrl

If you are binding your text box to width of column 1, all you need to do is leave out the Width property definition and set HorizontalAlignment = "Stretch"

如果您将文本框绑定到第 1 列的宽度,您需要做的就是省略 Width 属性定义并设置 HorizontalAlignment = "Stretch"

For example:

例如:

<Grid>
    <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50" />
            <ColumnDefinition Width="100" />
    </Grid.ColumnDefinitions>

    <TextBox Grid.Column = "1" HorizontalAlignment="Stretch" Height="120" Name="textBox1" />
</Grid>

The textbox now should be of height 120 and width 100.

文本框现在应该是高度 120 和宽度 100。