struct的一种用法

今天打开程序发现不对劲,三个按钮显示一样的Content。
查询代码,发现问题出现在

private void InitMenuData()
{
    HomeMenuItem menuItem = new HomeMenuItem();
    var dict = menuItem.ReadUnityConfig("MenuConfiguration");
    foreach (var item in dict.Values)
    {
        menuItem.Value = item;
        Pages.Add(menuItem);
    }
}

class是引用传递
所以HomeMenuItem添加的过程中,只添加了最后一个选项
将HomeMenuItem改为struct完美解决,
下面奉上全部代码

<ListBox
    x:Name="list"
    Height="40"
    ItemsSource="{Binding Pages}"
    Style="{DynamicResource StackPanelHorizontalListBox}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Border  BorderThickness="1">
                <DockPanel LastChildFill="True">
                    <Button
                        Height="32" Width="80"
                        Command="{s:Action ExecuteNavigatToView}"
                        CommandParameter="{Binding NavigatToView}"
                        Content="{Binding Value}" />
                </DockPanel>
            </Border>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
public class HomeViewModel: Screen
{      
    private BindableCollection<HomeMenuItem> _pages;

    public BindableCollection<HomeMenuItem> Pages
    {
        get => _pages??(_pages=new BindableCollection<HomeMenuItem>());
        set => SetAndNotify(ref _pages, value);
    }

    public HomeViewModel()
    {
        InitMenuData();
    }

    private void InitMenuData()
    {
        HomeMenuItem menuItem = new HomeMenuItem();
        var dict = menuItem.ReadUnityConfig("MenuConfiguration");
        foreach (var item in dict.Values)
        {
            //HomeMenuItem menuItem = new HomeMenuItem();        //使用struct的好处是这里是值传递,不需要重新构造数据
            menuItem.Value = item;
            Pages.Add(menuItem);
        }
    }
}
 public struct HomeMenuItem
 {
     public string Key { get; set; }
     public string Value { get; set; }

     public string NavigateToView { get; set; }

     /// <summary>
     /// 重置
     /// </summary>
     public void ResetItem()
     {
         this=new HomeMenuItem();
     }
 }

 public static class HomeMenuItemExtension
 {
     /// <summary>
     /// 读取WPF自带的App.config
     /// 这两个引用没有传递值,是读取config的值,所以不需要使用ref,
     /// 使用了struct后,如果传递数据的扩展方法,需要加上ref
     /// </summary>
     /// <param name="menuList"></param>
     public static Dictionary<string, string> ReadAppConfig(this HomeMenuItem menuList, string section)
     {
         IDictionary idict = (IDictionary)ConfigurationManager.GetSection(section);
         Dictionary<string, string> dict = idict.Cast<DictionaryEntry>().ToDictionary(de => de.Key.ToString(), de => de.Value.ToString());
         return dict;
     }

     /// <summary>
     /// 读取自定义的config文件
     /// </summary>
     /// <param name="menuList"></param>
     public static Dictionary<string, string> ReadUnityConfig(this HomeMenuItem menuList, string section)
     {
         Dictionary<string, string> dicts = new Dictionary<string, string>();
         ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap
         {
             ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + @"unity.config")
         };

         Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

         var customSection = (MenuConfiguration)config.GetSection(section);
         foreach (MenuElement menu in customSection.Menus)
         {
             dicts.TryAdd(menu.Title, menu.Value);
         }
         return dicts;

     }
 }
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<configSections>
		<section name="MenuConfiguration" type="IgniteApp.Common.MenuConfiguration,IgniteApp" />
	</configSections>
	<MenuConfiguration>
		<menus>
			<add title="001" value="标题1"/>
			<add title="002" value="标题2"/>
			<add title="003" value="标题3"/>
		</menus>
	</MenuConfiguration>
</configuration>
</unity>-->
posted @ 2024-10-09 00:00  孤沉  阅读(5)  评论(0编辑  收藏  举报