XAML 将元素的Width属性设置为另一个元素宽度的百分比

dba5bblo  于 2022-12-25  发布在  其他
关注(0)|答案(2)|浏览(161)

我有一个这样的网格:

<Grid HorizontalAlignment="Stretch">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"></ColumnDefinition>
        <ColumnDefinition Width="2*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <TextBlock Text="Rank Percentage" Grid.Column="0" />
    <Rectangle Height="20" Grid.Column="1" Width="{x:Bind CurrentCar.RankPercentage, Mode=OneWay}"
</Grid>

我希望矩形的宽度与列的宽度成比例。网格的宽度在编译时是未知的(它取决于用户如何调整应用程序窗口的大小)。例如:如果网格宽度为450,当前汽车等级百分比= 80,则矩形宽度应为450 (2/3)(80/100)
我曾尝试使用ConverterParameter = ActualWidth of the Grid的转换器,但它不起作用。

s8vozzvw

s8vozzvw1#

您可以在以下情况下使用网格的SizeChanged事件:

private void TheGrid_SizeChanged(object sender, SizeChangedEventArgs e)
{
    double rectangleWidth = TheGrid.ActualWidth;
    rectangleWidth *= (2.0 / 3.0);
    rectangleWidth *= (CurrentCar.RankPercentage / 100.0);
    TheRectangle.Width = rectangleWidth;
}

但是我认为你应该看看ProgressBar控件。

6mw9ycah

6mw9ycah2#

你可以使用valueConverter,但是你可能需要稍微修改一下Converter。你可以给Converter添加一个属性,并与你的根grid绑定,然后把元素名作为参数传递给Converter。然后你可以在Converter中得到Grid的宽度值。我做了一个简单的演示,你可以试试。

Xaml:

<Page.Resources>
    <local:MyValueConverter x:Key="MyValueConverter" UIParameter="{x:Bind MyGrid}" />
</Page.Resources>

<Grid x:Name="MyGrid" HorizontalAlignment="Stretch">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"></ColumnDefinition>
        <ColumnDefinition Width="2*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <TextBlock Text="Rank Percentage" Grid.Column="0" />
    <Rectangle Height="20" Grid.Column="1" Fill="Red"
               Width="{x:Bind CurrentCar.RankPercentage, Mode=OneWay, Converter={StaticResource MyValueConverter}}"/>
</Grid>

主页.cs:

this.Bindings.Update()中可能会有警告,但实际上并不重要

public ViewModel CurrentCar { get; set; }
    public MainPage()
    {
        this.InitializeComponent();
        CurrentCar= new ViewModel();
        CurrentCar.RankPercentage = 0.5;
        this.Loaded += MainPage_Loaded;
    }

    private void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        this.Bindings.Update();
    }
}
public class ViewModel 
{
    public double RankPercentage { get; set; }
}

public class MyValueConverter : IValueConverter 
{
    public UIElement UIParameter { get; set; }
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        double rankPercentage = System.Convert.ToDouble(value);
        double rectangleWidth=0;

        if (UIParameter != null)
        {
            Grid grid = UIParameter as Grid;
            double gridWidth = grid.ActualWidth;
            rectangleWidth = gridWidth * (2.0 / 3.0) * rankPercentage;
            return rectangleWidth;
        }

        return rectangleWidth;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

相关问题