更新时间:2022-12-05 14:32:29
我注册了 *** 只是为了参与这个问题.
I signed up for *** just so I could participate in this question.
在我在这里遇到这个问题之前,我搜索了 HOURS 来解决这个问题,然后我的希望破灭了,看到它已经在这里坐了将近一年没有答案.
I searched for HOURS for a solution to this before I ran across this question here, and then my hopes were dashed to see it's been sitting out here almost a year with no answer.
我之前发现了这个相关问题,它提供了我们试图用这个问题实现的基本解决方案,但没有提供任何有关使其实际工作的细节.如何从 powershell 使用 IValueConverter?
I had found this related question earlier, and it gives the basic solution we're trying to implement with this question, but doesn't give any details on making it actually work. How to use IValueConverter from powershell?
幸运的是,经过几个小时,并拼凑了很多其他信息,我终于解决了!
Luckily, after several more hours, and piecing together a lot of other info, I finally solved it!
它有 3 个部分.
SO,请参阅我发布的更新代码,其中包含以下更改.正如原始海报所示,此示例并未显示转换器的运行情况,但脚本至少会运行并显示表单而不会出错,表明表单本身接受了 TextBox 中的转换器定义和用法.
SO, see the updated code I posted which has the following changes. As the original poster indicated, this example doesn't show the converter in action, but the script will at least run and display the form without error, indicating the the form itself accepted the converter definition and usage in the TextBox.
代码
$src = @'
using System;
using System.Windows;
using System.Windows.Data;
using System.Globalization;
namespace MyConverter
{
public class DemoConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return "kuku";
}
else
{
return "bobo";
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
}
'@
Add-Type -AssemblyName PresentationFramework
Add-Type -TypeDefinition $src -ReferencedAssemblies PresentationFramework
#Checking that the new type works and convert is done...
$c = new-object MyConverter.DemoConverter
$AssemblyName = $c.gettype().Assembly.FullName.Split(',')[0]
#$c.Convert("gg", $null, $null, $null)
#$c.Convert(55, $null, $null, $null)
#Now declaring and loading the xaml
$inputXML = @'
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Converter="clr-namespace:MyConverter;assembly=myassembly"
xmlns:cnv="clr-namespace:MyProject" >
<Window.Resources>
<Converter:DemoConverter x:Key="TestConverter" />
</Window.Resources>
<Grid>
<TextBox x:Name="txtTestValue" Text="I'm here to show that xaml loading works!" />
<TextBox x:Name="txtTestValue2" Text="{Binding Path=Whatever, Converter={StaticResource TestConverter}}" />
</Grid>
</Window>
'@
[xml]$XAML = $inputXML -replace 'myassembly', $AssemblyName
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$Window=[Windows.Markup.XamlReader]::Load( $reader )
$Window.ShowDialog() | out-null