[英]How to control contents in a content view with a button in another content view in .Net Maui
[英]How to load a view with a converter in another assembly [MAUI.NET]
我有轉換器
using System.Globalization;
namespace WidgetsForRuntimeInjection.Converters
{
public class SampleBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{ ... }
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{ ... }
}
}
和一個視圖
<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:WidgetsForRuntimeInjection.ViewModels"
xmlns:converters="clr-namespace:WidgetsForRuntimeInjection.Converters;assembly=WidgetsForRuntimeInjection"
x:Class="WidgetsForRuntimeInjection.Views.SampleWidgetsForInjection">
<converters:SampleBooleanConverter x:Key="SampleBooleanConverter"/>
<DataTemplate x:DataType="viewModels:SwitchViewModel" x:Key="SwitchDataTemplate">
<Switch IsToggled="{Binding Value, Converter={StaticResource SampleBooleanConverter}}" IsEnabled="{Binding ReadWrite}"/>
</DataTemplate>
</ResourceDictionary>
它們都在構建為 dll 的單個程序集中。
然后在另一個程序集中我加載它並添加到應用程序資源。
var assembly = Assembly.LoadFile( ... path to dll... );
var resources = assembly.CreateInstance("WidgetsForRuntimeInjection.Views.SampleWidgetsForInjection");
App.Current.Resources.Add("SwitchDataTemplate", (resources as ResourceDictionary)["SwitchDataTemplate"]);
我得到了這樣的錯誤:
Microsoft.Maui.Controls.Xaml.XamlParseException: 'Position 7:6. Type converters:SampleBooleanConverter not found in xmlns clr-namespace:WidgetsForRuntimeInjection.Converters;assembly=WidgetsForRuntimeInjection'
但是我可以在前一行(在第二個程序集中)創建這個轉換器的一個實例。
var converter = assembly.CreateInstance("WidgetsForRuntimeInjection.Converters.SampleBooleanConverter");
當然,在沒有轉換器的情況下,這一切都非常有效。
如何讓它發揮作用? 我嘗試將 Converter 作為 DynamicResource 並以不同方式為轉換器聲明名稱空間。
更新:
這有點奇怪,因為在我以替代方式添加相同內容后它似乎可以工作 - 在 xaml.cs 文件中,如下所示:
public partial class SampleWidgetsForInjection : ResourceDictionary
{
public SampleWidgetsForInjection()
{
this.Add("SampleBooleanToColorConverter", new SampleBooleanToColorConverter());
InitializeComponent();
}
}
所以這似乎是一種解決方法/解決方案:
public partial class SampleWidgetsForInjection : ResourceDictionary
{
public SampleWidgetsForInjection()
{
this.Add("SampleBooleanToColorConverter", new SampleBooleanToColorConverter());
InitializeComponent();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.