2016-06-30 15 views
1

Ich habe diese Benutzerkontrolle gemacht:Ändern benutzerdefinierte Usercontrol programmatisch

<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> 

Ich muss in der Lage, die Grenze Hintergrundfarbe und Text in den Textblocks zu ändern. Wenn ich jedoch ein neues benutzerdefiniertes Steuerelement erstelle, kann ich es nicht einstellen.

Ich versuchte dies:

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

oder dieses:

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

Antwort

0

Sie können Benutzer die Kontrolle durch die Definition von Eigenschaften wie folgt

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;    
    } 
} 

Verwendung binden:

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

Ich habe gerade eine Klasse mit den definierten Eigenschaften erstellt und den Datacontext für das erstellte Modell festgelegt, aber das scheint besser zu sein. – Dracke

+0

Ja, diese Logik sollte auch funktionieren. und das funktioniert auch –

Verwandte Themen