gpt4 book ai didi

c# - 从 IValueConverter 获取对代码隐藏类实例的引用

转载 作者:行者123 更新时间:2023-12-02 22:19:12 24 4
gpt4 key购买 nike

我有这个代码:

namespace Test
{
public partial class SearchField : UserControl
{
public SearchStrategy Strategy { get; set; }
public SearchField() { InitializeComponent(); }
}

public class TextToTipConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
SearchStrategy Strategy = // How do I get reference to SearchField.Strategy from here?

return Strategy.parseInput<string> (value.ToString(), (first, inp) => Strategy.tipMap.ContainsKey(first) && inp.Length == 1 ? first + Strategy.tipMap[first] : "", AppResources.GeneralSearchTip);
}

public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}

XAML 代码:

<UserControl.Resources>
<controls:TextToTipConverter x:Key="TextToTip" />
</UserControl.Resources>
...
<TextBox x:Name="Search" Grid.Column="0" Canvas.ZIndex="1"
Style="{StaticResource SearchBoxStyle}" Foreground="{StaticResource PhoneForegroundBrush}" />

<TextBox x:Name="Tip" Grid.Column="0" Canvas.ZIndex="0" IsReadOnly="True"
Style="{StaticResource SearchBoxStyle}" Opacity="0.5" Foreground="{StaticResource PhoneAccentBrush}"
Text="{Binding ElementName=Search, Converter={StaticResource TextToTip}, Path=Text}" />

SearchFieldSearchStrategy Strategy 有一些我需要从 TextToTipConverter 访问的方法和字段。我怎样才能得到它?

最佳答案

SearchField.xaml 是 View ,SearchField.xaml.cs 是背后的代码。您可以在 msdn 上阅读有关 MVVM、数据绑定(bind)和 ViewModel 的信息。您可以创建一个名为 ViewModel 的类,您将在其上绑定(bind)数据。例如,假设有以下类:

public class SearchViewModel : INotifyPropertyChanged
{
public string Text { get; set; }
public SearchStrategy Strategy { get; set; }
}

您的 SearchField.xaml.cs 将是:

public partial class SearchField : UserControl
{
private SearchViewModel viewModel;

public SearchField()
{
this.viewModel = new SearchViewModel ();
this.DataContext = this.viewModel;
}
}

现在在你的 xaml 中,

TextBox x:Name="Search" Text="{Binding Text}"

将 viewModel 中的数据与 TextBox 绑定(bind)你将能够做到:

TextBox x:Name="Tip" Text="{Binding, Converter={StaticResource TextToTip}, Path=Text}"

在转换器中,名为 value 的参数将是您可以在其上获取属性的 View 模型:

SearchViewModel vm = (SearchViewModel) value;
vm.Strategy;
vm.Text

不知道我说的对不对

关于c# - 从 IValueConverter 获取对代码隐藏类实例的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13995456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com