从IValueConverter获取代码隐藏类实例的引用

本文关键字:引用 实例 代码隐藏类 IValueConverter 获取 | 更新日期: 2023-09-27 17:49:25

我有这样的代码:

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访问的方法和字段。我怎么去那儿?

从IValueConverter获取代码隐藏类实例的引用

SearchField。xaml是视图,而SearchField.xaml.cs是背后的代码。您可以在msdn上阅读有关MVVM,数据绑定和ViewModel的信息。您可以创建一个名为ViewModel的类,并在其上绑定数据。例如,想象下面的类:

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

你的searchfield . example .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绑定在一起你可以这样做:

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

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

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

我不知道我是否清楚。

我认为与其将Tip文本框直接绑定到Search文本框,不如尝试在Search文本框和SearchFieldViewModel中的属性之间创建一个双向绑定。这将导致对Search文本框的更改自动下推到SearchFieldViewModel中。

一旦搜索字符串在SearchFieldViewModel中,您就可以将它与SearchStrategy捆绑到TipViewModel中,并使用TipViewModel作为提示文本框的DataContext。请看下面的代码:

SearchField.xaml

<UserControl x:Class="SilverlightApplication.SearchField"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:SilverlightApplication"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <local:TextToTipConverter x:Key="TextToTip" />
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White">
        <TextBox x:Name="Search" Grid.Column="0" Canvas.ZIndex="1" Text="{Binding Path=SearchString, Mode=TwoWay}"
                 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 Path=TipViewModel, Converter={StaticResource TextToTip}}"/>
    </Grid>
</UserControl>

SearchField.xaml.cs

public partial class SearchField : UserControl
{
   public SearchField()
   {
       InitializeComponent();
       this.Loaded += (s, e) => this.LayoutRoot.DataContext = new SearchFieldViewModel();
    }
}

SearchFieldViewModel.cs

public class SearchFieldViewModel
{
    public string SearchString { get; set; }
    public SearchStrategy SearchStrategy { get; set; }
    public TipViewModel TipViewModel
    {
        get
        {
            return new TipViewModel
            {
                SearchString = this.SearchString,
                SearchStrategy = this.SearchStrategy
            };
        }
    }
}

TipViewModel.cs

public class TipViewModel
{
    public string SearchString { get; set; }
    public SearchStrategy SearchStrategy { get; set; }
}

TextToTipConverter.cs

public class TextToTipConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        TipViewModel tipViewModel = value as TipViewModel;
        SearchStrategy strategy = tipViewModel.SearchStrategy;
        string searchString = tipViewModel.SearchString;
        return Strategy.parseInput<string>(searchString , (first, inp) => strategy.tipMap.ContainsKey(first) && inp.Length == 1 ? first + strategy.tipMap[first] : "", AppResources.GeneralSearchTip);
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

把你的SearchStrategy放到ViewModel中,并使用Binding传递它。我不知道我是否能回答你的问题,多给点信息