Как я могу изменить ширину TextBox с длиной текста? - PullRequest
0 голосов
/ 23 ноября 2018

Я хочу переделать одну разновидность игры из тех игр, в которые вводятся слова, и вы должны правильно записать это слово.

Вот один из них: https://www.youtube.com/watch?v=FqNTKJRBPdc

Моя первая проблема в том, что я ничего не нахожу, как я могу динамически изменять ширину TextBox.

Так что, если все слово не помещается в TextBox, я хочу увеличить ширину TextBox.Как я мог это сделать?

Вот мой вид:

<UserControl x:Class="Prog_korny.View.GameView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Prog_korny"
             xmlns:vm="clr-namespace:Prog_korny.ViewModel"
             mc:Ignorable="d" 
             d:DesignHeight="720" d:DesignWidth="1280" Name="alUO">
    <UserControl.Resources>
        <vm:GameViewModel  x:Key="GameViewModel"/>
    </UserControl.Resources>
    <Grid DataContext="{Binding Source={StaticResource GameViewModel}}">
        <Grid.Background>
            <ImageBrush ImageSource="/Prog korny;component/Pictures/background.png"/>
        </Grid.Background>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="2*" />
            <ColumnDefinition Width="5*" />
            <ColumnDefinition Width="3*" />
            <ColumnDefinition Width="4*" />
            <ColumnDefinition Width="3*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="7*" />
            <RowDefinition Height="1*" />
            <RowDefinition Height="6*" />
            <RowDefinition Height="1*" />
        </Grid.RowDefinitions>
        <Canvas Grid.ColumnSpan="5" Grid.RowSpan="4"></Canvas>
        <TextBox x:Name="txtText" Grid.Column="2" Grid.Row="1" Grid.ColumnSpan="1" Background="Transparent" Foreground="White" BorderBrush="Blue" FontFamily="Bebas Neue" FontSize="35" TextAlignment="Center" VerticalAlignment="Center" Cursor="Hand">
            <TextBox.Text>
                <Binding Path="textContent" UpdateSourceTrigger="PropertyChanged"/>
            </TextBox.Text>
        </TextBox>
        <Label x:Name="lblLevel" Grid.Column="0" Grid.Row="4" Grid.ColumnSpan="1"  Foreground="White" BorderBrush="{x:Null}" FontFamily="Bebas Neue" FontSize="30" Cursor="Hand">
            <Label.Content>
                <Binding Path="LevelLabel" UpdateSourceTrigger="PropertyChanged"/>
            </Label.Content>
        </Label>
        <Label x:Name="lblScore" Grid.Column="4" Grid.Row="4" Grid.ColumnSpan="1" Foreground="White" BorderBrush="{x:Null}" FontFamily="Bebas Neue" FontSize="30" Cursor="Hand">
            <Label.Content>
                <Binding Path="ScoreLabel" UpdateSourceTrigger="PropertyChanged"/>
            </Label.Content>
        </Label>
    </Grid>
</UserControl>

ViewModel:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Prog_korny.ViewModel
{
    class GameViewModel : ViewModelBase
    {
        private string _textContent;

        public string TextContent
        {
            get { return _textContent; }
            set { _textContent = value; }
        }

        private string _levelLabel = "Level: 0";

        public string LevelLabel
        {
            get { return _levelLabel; }
            set { _levelLabel = value; }
        }

        private string _scoreLabel = "Score: 0";

        public string ScoreLabel
        {
            get { return _scoreLabel; }
            set { _scoreLabel = value; } 
        }
    }
}

1 Ответ

0 голосов
/ 24 ноября 2018

вы можете определить свойство, которое вы будете связывать со свойством width на странице xaml.Вы можете управлять свойством из viewmodel в зависимости от вашего состояния.Вы можете управлять практически всем, что доступно вам на вашей странице xaml окна. Плюс вы можете определить условную логику, основанную на сопряжении двух свойств.например, если ваше свойство TextContent достигает определенного предела, задайте для свойства ширины текста что-то еще.

При низком уровне управления вы можете добиться контроля ширины с помощью триггеров данных.

<Style>
  <Setter Property="Width" Value="200"/>
  <Style.Triggers>
    <<Put your conditions which will set the value>>
  </Style.Triggers>
</Style>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...