将Xaml代码转换为c#
本文关键字:转换 代码 Xaml | 更新日期: 2023-09-27 18:14:22
我需要在以下代码中将XAML转换为c#。
它在设计时工作良好。
但是我想在运行时赋值。下面是XAML代码
<ListBox Height="550" Name="listBox1" Width="398" FontFamily="Calibri" Opacity="20" FontStretch="Normal" SelectedIndex="1" FontWeight="Bold" FontStyle="Normal" FontSize="28" HorizontalAlignment="Center" VerticalAlignment="Center" HorizontalContentAlignment="Center" SelectionChanged="listBox1_SelectionChanged" BorderBrush="#FF828790" Foreground="Red" OpacityMask="{x:Null}">
<Border CornerRadius="6" BorderBrush="Black" Background="White" BorderThickness="1" DockPanel.Dock="Top" AllowDrop="True">
<StackPanel Orientation="Horizontal" DataContext="{Binding}" Width="288">
<Image Source="/final;component/Images/shawshank.jpg" Width="75" Stretch="Fill" DataContext="{Binding}" FlowDirection="LeftToRight" Height="75"></Image>
<StackPanel Orientation="Vertical" DataContext="{Binding}" Width="288">
<TextBlock Text="The Shawshank" FlowDirection="LeftToRight" VerticalAlignment="Center" HorizontalAlignment="Left" FontFamily="Segoe UI" FontSize="22" Foreground="Black"></TextBlock>
<Image Height="22" Source="/final;component/Images/fivestars.png" Width="100" IsManipulationEnabled="False" Stretch="Fill" StretchDirection="Both" FlowDirection="LeftToRight" DataContext="{Binding}" Margin="0" AllowDrop="False" ClipToBounds="False" Focusable="False" OverridesDefaultStyle="False" UseLayoutRounding="False" HorizontalAlignment="Left"></Image>
<TextBlock Text=" By:Frank Darabont" FlowDirection="LeftToRight" VerticalAlignment="Center" HorizontalAlignment="Left" FontFamily="Segoe UI" FontSize="18" Foreground="Black" FontWeight="Normal"></TextBlock>
</StackPanel>
</StackPanel>
</Border>
</ListBox>
不需要将整个XAML转换为c#来完成此操作。如果你想在c#中设置值,你的控件需要一个名称。要命名控件,请在XAML:
中执行以下操作:<Control x:Name="MyNamedControl" />
你可以在c#中这样做:
MyNamedControl.PropertyToSet = Value;
首先要给每个控件分配一个Name=""
,然后在你的c#代码中,你可以使用它们的名称访问这些值。
ControlName.Property = Property.Value;
这是一个简单的方法,您可以访问当前存在的控件,或者您可以在运行时创建自己的控件,然后为它们赋值并将它们附加到软件显示
您可以像这样在后面的代码中为元素添加控件和属性:-
//Creating Controls
ListBox l1 = new ListBox();
l1.Height = 550;
l1.Width = 398;
//Adding Property to controls
l1.VerticalAlignment = System.Windows.VerticalAlignment.Center;
l1.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
l1.Name = "listBox1";
Border bd = new Border();
StackPanel sp = new StackPanel();
Button btn = new Button();
//Adding Controls to the Containers
sp.Childern.Add(btn);
bd.Child = sp;
l1.Items.Add(sp);