繁体   English   中英

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

[英]Get reference to code-behind class instance from IValueConverter

我有这个代码:

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 是视图,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}"

将 viewModel 中的数据与 TextBox 绑定,您将能够执行以下操作:

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

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

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

我不知道我是否清楚。

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

一旦搜索字符串位于 SearchFieldViewModel 中,您就可以将其与 SearchStrategy 捆绑到一个 TipViewModel 中,并将 TipViewModel 用作您的 Tip 文本框的 DataContext。 请参阅下面的代码。

搜索字段.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
            };
        }
    }
}

提示视图模型.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 传递它。 我不知道我是否回答了您的问题,请提供更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM