C# WPF用什么布局让里面的图片自动排列

C# WPF用什么布局让里面的图片自动排列,第1张

以字符串为例给你举个例子。

主要使用UnifromGrid布局,通过转换器来计算行数。

如有疑问,继续追问。

XAML代码

    <Grid>

        <Grid.RowDefinitions>

            <RowDefinition Height="*"/>

            <RowDefinition Height="auto"/>

        </Grid.RowDefinitions>

        <ListBox x:Name="lb" ItemsSource="{Binding LBSource}">

            <ListBox.Resources>

                <local:RowConverter x:Key="RowConverter"/>

            </ListBox.Resources>

            <ListBox.ItemsPanel>

                <ItemsPanelTemplate>

                    <UniformGrid Rows="{Binding ElementName=lb,Path=ItemsSource,Converter={StaticResource RowConverter},Mode=OneWay}"/>

                </ItemsPanelTemplate>

            </ListBox.ItemsPanel>

        </ListBox>

        <Button Grid.Row="1" Content="添加一个" Click="Button_Click"/>

    </Grid>

CS代码:

    public partial class Window1 : Window

    {

        public List<string> LBSource

        {

            get { return (List<string>)GetValue(LBSourceProperty) }

            set { SetValue(LBSourceProperty, value) }

        }

        public static readonly DependencyProperty LBSourceProperty =

            DependencyProperty.Register("LBSource", typeof(List<string>), typeof(Window1))

        public Window1()

        {

            InitializeComponent()

            LBSource = new List<string>() { "text1" }

            this.DataContext = this

        }

        private void Button_Click(object sender, RoutedEventArgs e)

        {

            List<string> list =new List<string>( LBSource)

            list.Add("text" + (LBSource.Count + 1).ToString())

            LBSource = list

        }

    }

转换器代码:

    public class RowConverter : IValueConverter

    {

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

        {

            if (value == null)

            {

                return 0

            }

            int i = (value as IList).Count

            if (i <= 2)

            {

                return i

            }

            else if (i <= 6)

            {

                return 3

            }

            else

            {

                return 4

            }

        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

        {

            throw new NotImplementedException()

        }

    }

实现效果:

在这种情况下不用转换器。

你定义下listbox的item属性,在里面添加一个文本显示姓名就行了。示例代码:

<ItemsControl.ItemTemplate>

<DataTemplate>

<StackPanel Orientation="Horizontal" >

<TextBlock Text="{Binding Path=PatientName}"/>

<TextBlock Text=":"/>

<TextBlock Text="{Binding Path=Position}"/>

</StackPanel>

</DataTemplate>

</ItemsControl.ItemTemplate>

PatientName、Position为绑定的类的属性


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11799567.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-18
下一篇2023-05-18

发表评论

登录后才能评论

评论列表(0条)

    保存