簡體   English   中英

以編程方式修改自定義UserControl

[英]Modify custom UserControl programmatically

我做了這個用戶控件:

<UserControl
    x:Class="ScannerApp.Custom_Controls.LocationAndQuantity"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ScannerApp.Custom_Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="20">
    <Grid Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Border x:Name="border" Background="{Binding Color}">
            <TextBlock x:Name="locationTxt" Text="{Binding Location}" HorizontalAlignment="Center"></TextBlock>
        </Border>
        <TextBlock x:Name="quantityTxt" Text="{Binding Quantity}" Grid.Column="1" HorizontalAlignment="Center" TextWrapping="Wrap" VerticalAlignment="Top"/>
    </Grid>
</UserControl>

我需要能夠修改TextBlocks中的邊框Background顏色和文本。 但是,如果創建新的“自定義”控件,則無論如何都無法設置它。

我嘗試了這個:

LocationAndQuantity customControl = new LocationAndQuantity(Color = "red", Location = "A-01-01", Quantity = "23");

或這個:

LocationAndQuantity customControl = new LocationAndQuantity();
customContrl.border = ... //this just gives me error right away.

您可以通過以下方式定義屬性來綁定用戶控件

public partial class LocationAndQuantity : UserControl
{
    public Brush Color { get; set; }
    public string  Location { get; set; }
    public int Quantity { get; set; }

    //The class must have default constructor
    public LocationAndQuantity()
    {
        this.InitializeComponent();
    }

    public LocationAndQuantity(string c,string l, int q)
    {
        this.Color = new SolidColorBrush((Color)ColorConverter.ConvertFromString(c));
        this.Location = l;
        this.Quantity = q;
        InitializeComponent();
        DataContext = this;            
    }
}

采用:

LocationAndQuantity customControl = new LocationAndQuantity("red", "A-01-01", 10);
//then add to stackpannel for example
stackPanel.Children.Add(customControl);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM