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

时间:2012-12-21 18:39:24

标签: c# reference code-behind windows-phone-8

我有这段代码:

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}" />

SearchField的{​​{1}}有一些我需要从SearchStrategy Strategy访问的方法和字段。 我该怎么做到?

3 个答案:

答案 0 :(得分:2)

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

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}” 将使用TextBox绑定viewModel中的数据 你将能够做到:     TextBox x:Name =“Tip”Text =“{Binding,Converter = {StaticResource TextToTip},Path = Text}”

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

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

我不知道我是否清楚。

答案 1 :(得分:2)

我认为不是将Tip文本框直接绑定到“搜索”文本框,而是尝试在“搜索”文本框和SearchFieldViewModel中的属性之间创建双向绑定。这将导致对“搜索”文本框的更改自动下推到SearchFieldViewModel中。

一旦搜索字符串在SearchFieldViewModel中,您就可以将它与SearchStrategy一起捆绑到TipViewModel中,并使用TipViewModel作为Tip文本框的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();
    }
}

答案 2 :(得分:1)

将您的SearchStrategy放入ViewModel并使用Binding传递它。我不知道我是否回答你的问题,提供更多信息