1

Как выводить широту элемента на экран с использованием синтаксиса самого C# даже при изменении ширины элемента сплиттером? То есть перетащив сплиттер в сторону - вместо чисел в выделенных красных квадратах отображалась бы ширина каждого прямоугольника в котором находится число.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="2*"/>
        <RowDefinition Height="1*"/>
    </Grid.RowDefinitions>
    <Grid Grid.ColumnSpan="3">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="1*"/>
        </Grid.RowDefinitions>
        <Grid Grid.ColumnSpan="3" Grid.Row="2">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <GridSplitter Grid.Column="1" Grid.Row="0" 
                      ShowsPreview="False" Width="3"
                      HorizontalAlignment="Center" 
                      VerticalAlignment="Stretch" />
            <Canvas Grid.Column="0" 
                    Background="GreenYellow">
                <TextBlock Text="3"/>
            </Canvas>
            <Canvas Grid.Column="2" 
                    Background="Green">
                <TextBlock Text="4"/>
            </Canvas>
        </Grid>
        <GridSplitter Grid.Column="1" Grid.Row="0" 
                      ShowsPreview="False" Width="3"
                      HorizontalAlignment="Center" 
                      VerticalAlignment="Stretch" />
        <Canvas Grid.Column="0" Background="NavajoWhite" Grid.Row="0">
            <TextBlock Text="1"/>
        </Canvas>
        <Canvas Grid.Column="2" Grid.Row="0" Background="Purple">
            <TextBlock Text="2"/>
        </Canvas>
    </Grid>
    <GridSplitter Grid.Column="1" Grid.Row="1" 
                  ShowsPreview="False" Width="3"
                  HorizontalAlignment="Center" 
                  VerticalAlignment="Stretch" />
    <Canvas Grid.Column="0" Grid.Row="1" Background="Blue">
        <TextBlock Text="5"/>
    </Canvas>
    <Canvas Grid.Column="2" Grid.Row="1" Background="Yellow">
        <TextBlock Text="6"/>
    </Canvas>
</Grid>
10
  • 1
    Попробуйте так <TextBlock Text="{Binding ActualWidth, RelativeSource={RelativeSource Self}}"/> или так <TextBlock Text="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType=Canvas}}"/>
    – aepot
    30 ноя 2020 в 23:09
  • Кстати, непонятно, зачем вам здесь канвасы, если можно их убрать и задать цвет фона самому текстблоку.
    – aepot
    30 ноя 2020 в 23:21
  • @aepot ,Спасибо за ответ выше, а про канвас... его ещё нужно будет превратить в кнопку, которую можно было бы растягивать(ведь вправо их должно быть штук 20-30 да и вниз в пару раз больше и вдобавок ещё ScrollBar вертикальный и горизонтальный :) ) и при нажатии она меняла бы цвет. В общем кошкин дом) В вопросе разукрашены для видимости разделения 30 ноя 2020 в 23:29
  • Сработало? Что именно сработало?
    – aepot
    30 ноя 2020 в 23:31
  • @aepot Со вторым вариантом. А как обратиться к Text элемента в коде C#? 30 ноя 2020 в 23:36

1 ответ 1

1

Попробуйте так

<TextBlock Text="{Binding ActualWidth, RelativeSource={RelativeSource Self}}"/>

или так

<TextBlock Text="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType=Canvas}}"/>

Лучше не делайте дерево гридов, лучше сделайте один старший грид, отвечающий за высоту вложенных гридов, и внутри 3 грида со сплиттерами. Это позволит избежать большой вложенности, если надо много таких строчек. Грубо говоря, вместо <Grid>1<Grid>2<Grid>3</Grid></Grid></Grid> сделайте <Grid><Grid>1</Grid><Grid>2</Grid><Grid>3</Grid></Grid>. Один лишний грид, но читаемость разметки будет значительно лучше.

У меня вот так получилось. Вместо Canvas использовал Border, так как первый предназначен для всяких фигур, и он не очень подходит под текущую ситуацию по поведению.

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.Resources>
        <Style TargetType="{x:Type GridSplitter}">
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Stretch"/>
            <Setter Property="ShowsPreview" Value="False"/>
            <Setter Property="Width" Value="3"/>
        </Style>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="Text" Value="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType=Border}, StringFormat=F2}"/>
            <Setter Property="Padding" Value="5"/>
            <Setter Property="FontSize" Value="20"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
        </Style>
    </Grid.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <GridSplitter Grid.Column="1"/>
        <Border Background="NavajoWhite">
            <TextBlock/>
        </Border>
        <Border Grid.Column="2" Background="Purple">
            <TextBlock/>
        </Border>
    </Grid>
    <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <GridSplitter Grid.Column="1"/>
        <Border Background="Blue">
            <TextBlock/>
        </Border>
        <Border Grid.Column="2" Background="Yellow">
            <TextBlock/>
        </Border>
    </Grid>
    <Grid Grid.Row="2">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <GridSplitter Grid.Column="1"/>
        <Border Background="GreenYellow">
            <TextBlock/>
        </Border>
        <Border Grid.Column="2" Background="Green">
            <TextBlock/>
        </Border>
    </Grid>
</Grid>

введите сюда описание изображения

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.