标签: ivalueconverter

如何在WPF ComboBox中使用MultiBinding

这让我坚持不懈!

ComboBox习惯过滤员工的查询工作正常,但只显示员工的名字.我想使用a MultiValueConverter来显示员工的全名(如果我们没有2个Mikes和2个Daves,那就不那么紧急了)

下面是我的工作代码和IMultiValueConverter类(为了简洁,修剪了不必要的格式).我已经尝试了一切我能想到的让MultiConverter工作但我没有运气.

<ComboBox ItemsSource="{Binding Path=EmployeesFilter}" 
                       DisplayMemberPath="EmpFirstName"
                       SelectedValue="{Binding Path=EmployeeToShow, Mode=TwoWay}"/>
Run Code Online (Sandbox Code Playgroud)

它绑定的ViewModel属性:

// This collection is used to populate the Employee Filter ComboBox
private ObservableCollection<Employee> employeesFilter;
public ObservableCollection<Employee> EmployeesFilter
{
    get {
            return employeesFilter;
        }
    set {
        if (employeesFilter != value)
        {
            employeesFilter = value;
            OnPropertyChanged("EmployeesFilter");
        }
    }
}

// This property is TwoWay bound to the EmployeeFilters SelectedValue
private Employee employeeToShow;
public Employee EmployeeToShow
{
    get {
            return employeeToShow;
        }
    set {
        if (employeeToShow …
Run Code Online (Sandbox Code Playgroud)

c# data-binding wpf xaml ivalueconverter

6
推荐指数
1
解决办法
3万
查看次数

在双向绑定中使用IValueConverter和当前的DataContext

我遇到了转换器的问题,我用它来转换字符串和我们的时间格式.转换器本身工作正常,并实现如下:

    [ValueConversion(typeof(string), typeof(SimpleTime))]
    public class StringToSimpleTimeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // convert from string to SimpleTime and return it
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // convert value from SimpleTime to string and return it
        }
    }
Run Code Online (Sandbox Code Playgroud)

使用转换器的XAML在usercontrol.resources中包含转换器本身,如下所示:

<converter:StringToSimpleTimeConverter x:Key="stringToSimpleTimeConverter"/>
Run Code Online (Sandbox Code Playgroud)

如果遇到属性(我在后台使用wpf工具包中的datagrid),则使用用于编辑simpletime的datatemplate:

<DataTemplate x:Key="SimpleTimeEditingTemplate">
        <TextBox Text="{Binding, Converter={StaticResource stringToSimpleTimeConverter}, Mode=TwoWay}"/>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是转换器需要在绑定中指定路径,如果它是双向转换器(我需要在两个方向),但我想要设置的属性已经是当前的DataContext - 什么路径那我可以指定吗?

我能想到的唯一解决方法是在SimpleTime中引入一个虚拟属性,它只获取当前的SimpleTime或设置它.

public class SimpleTime
{
    ...
    public SimpleTime Clone
    {
        get { …
Run Code Online (Sandbox Code Playgroud)

data-binding wpf datacontext converter ivalueconverter

6
推荐指数
1
解决办法
6851
查看次数

将转换后的Enum绑定到ComboBox

我试图将以下枚举绑定到ComboBox

Public Enum PossibleActions
  ActionRead
  ActionWrite
  ActionVerify
End Enum
Run Code Online (Sandbox Code Playgroud)

我不能改变Enum本身,但我不想显示这些字符串.我的目的只是剪切前缀'Action'并在ComboBox中显示'Read','Write'和'Verify'.因此我写了一个ValueConverter

Public Class PossibleActionsConverter
  Implements IValueConverter

      Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        Dim actions() As PossibleActions
        Dim strings() As String

        actions = CType(value, PossibleActions())
        ReDim strings(actions.GetUpperBound(0))
        For i = 0 To actions.GetUpperBound(0)
          strings(i) = actions(i).ToString.Substring(6)
        Next
        Return strings
      End Function

      Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal …
Run Code Online (Sandbox Code Playgroud)

vb.net wpf binding ivalueconverter

6
推荐指数
1
解决办法
1669
查看次数

从转换器返回动态资源

我想根据bool的状态更改WPF控件的颜色,在这种情况下是复选框的状态.只要我使用StaticResources,这个工作正常:

我的控制

<TextBox Name="WarnStatusBox" TextWrapping="Wrap" Style="{DynamicResource StatusTextBox}" Width="72" Height="50" Background="{Binding ElementName=WarnStatusSource, Path=IsChecked, Converter={StaticResource BoolToWarningConverter}, ConverterParameter={RelativeSource self}}">Status</TextBox>
Run Code Online (Sandbox Code Playgroud)

我的转换器:

[ValueConversion(typeof(bool), typeof(Brush))]

public class BoolToWarningConverter : IValueConverter
{
    public FrameworkElement FrameElem = new FrameworkElement();

    public object Convert(object value, Type targetType,
        object parameter, CultureInfo culture)
    {                      
        bool state = (bool)value;
        try
        {              
            if (state == true)
                return (FrameElem.TryFindResource("WarningColor") as Brush);
            else
                return (Brushes.Transparent);
        }

        catch (ResourceReferenceKeyNotFoundException)
        {
            return new SolidColorBrush(Colors.LightGray);
        }
    }

    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        return …
Run Code Online (Sandbox Code Playgroud)

wpf ivalueconverter dynamicresource

6
推荐指数
1
解决办法
5422
查看次数

IValueConverter不适用于SolidColorBrush

我有一个进度条,我想根据布尔值改变颜色; true为绿色,false为红色.我有代码似乎应该工作(它将它绑定到文本框时返回正确的值)但不是当它是进度条的颜色属性时.转换器定义为此(在App.xaml.cs中,因为我想在任何地方访问它):

public class ProgressBarConverter : System.Windows.Data.IValueConverter
{
    public object Convert(
        object o, 
        Type type, 
        object parameter, 
        System.Globalization.CultureInfo culture)
    {
        if (o == null)
            return null;
        else
            //return (bool)o ? new SolidColorBrush(Colors.Red) : 
            //                 new SolidColorBrush(Colors.Green);
            return (bool)o ? Colors.Red : Colors.Green;
    }

    public object ConvertBack(
        object o, 
        Type type, 
        object parameter, 
        System.Globalization.CultureInfo culture)
    {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我将以下内容添加到App.xaml(因此它可以是全局资源):

<Application.Resources>
    <local:ProgressBarConverter x:Key="progressBarConverter" />
    <DataTemplate x:Key="ItemTemplate">
        <StackPanel>
            <TextBlock Text="{Binding name}" Width="280" />
            <TextBlock Text="{Binding isNeeded, 
                          Converter={StaticResource progressBarConverter}}" />
            <ProgressBar>
                <ProgressBar.Foreground> …
Run Code Online (Sandbox Code Playgroud)

data-binding silverlight ivalueconverter windows-phone-7

6
推荐指数
1
解决办法
1599
查看次数

使用Unity将对象注入IValueConverter实例

我在Silverlight 5项目中有一个IValueConverter实例,它将自定义数据转换为不同的颜色.我需要从数据库中读取实际的颜色值(因为这些可以由用户编辑).

由于Silverlight使用异步调用通过Entity Framework从数据库加载数据,因此我创建了一个简单的存储库,它保存数据库中的值.

界面:

public interface IConfigurationsRepository
{
    string this[string key] { get; }
}
Run Code Online (Sandbox Code Playgroud)

实施:

public class ConfigurationRepository : IConfigurationsRepository
{
    private readonly TdTerminalService _service = new TdTerminalService();

    public ConfigurationRepository()
    {
        ConfigurationParameters = new Dictionary<string, string>();
        _service.LoadConfigurations().Completed += (s, e) =>
            {
                var loadOperation = (LoadOperation<Configuration>) s;
                foreach (Configuration configuration in loadOperation.Entities)
                {
                    ConfigurationParameters[configuration.ParameterKey] = configuration.ParameterValue;
                }
            };
    }

    private IDictionary<string, string> ConfigurationParameters { get; set; }

    public string this[string key]
    {
        get
        {
            return ConfigurationParameters[key];
        }
    } …
Run Code Online (Sandbox Code Playgroud)

c# ioc-container unity-container ivalueconverter silverlight-5.0

6
推荐指数
2
解决办法
3513
查看次数

将ValueConverter存储到变量

我有一个ValueConverter用于绑定StoryBoard动画中的'To'Value,类似于答案 - WPF动画:绑定到storyboard动画的"To"属性.

问题是我MultiBinding ValueConverter在几个地方重复下面的代码.

    <MultiBinding Converter="{StaticResource multiplyConverter}">
       <Binding Path="ActualHeight" ElementName="ExpanderContent"/>
       <Binding Path="Tag" RelativeSource="{RelativeSource Self}" />
    </MultiBinding>
Run Code Online (Sandbox Code Playgroud)

我想通过将结果存储ValueConverter到资源变量来删除此重复代码,以便我可以将此本地变量直接绑定到故事板.

<system:Double x:Key="CalculatedWidth">
    <MultiBinding Converter="{StaticResource multiplyConverter}">
        <Binding Path="ActualHeight" ElementName="ExpanderContent"/>
        <Binding Path="Tag" RelativeSource="{RelativeSource Self}" />
    </MultiBinding>
</system:Double >
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

"Double"类型不支持直接内容.

无法将内容添加到"Double"类型的对象.

我觉得这是一个常见问题,但无法找到解决方案来消除这种冗余.

更新

谢谢Rohit,你的答案解决了这个问题.但我还有一个相关的问题,所以更新问题.这个变量CalculatedWidth在正常情况下工作正常,但是当它在RenderTransform中使用时,它不会获取值.即如果我使用正常的方式使用转换器它可以工作,但它不会获取变量.

<StackPanel.RenderTransform>
    <TranslateTransform x:Name="SliderTransform">
        <TranslateTransform.X>
            <Binding Converter="{StaticResource PanelConverter}" ElementName="SliderPanel" Path="ActualWidth" /> // Works
            <Binding Path="Width" Source="{StaticResource CalculatedWidth}"/> // Doesn't Work
        </TranslateTransform.X>
    </TranslateTransform>
</StackPanel.RenderTransform>
Run Code Online (Sandbox Code Playgroud)

我将变量保留为本地资源的一部分.这是否意味着在调用Render变换时不会创建变量?

c# wpf xaml ivalueconverter

6
推荐指数
1
解决办法
328
查看次数

为什么WPF中同时具有TypeConverters和IValueConverter?

我是WPF的新手。我只是不明白为什么WPF中需要TypeConverters和IValueConverter。这两个对象的目的是将值转换为特定类型。但是为什么两者都有呢?

提前致谢。

wpf typeconverter ivalueconverter

6
推荐指数
1
解决办法
1090
查看次数

DataContext作为资源中转换器绑定的源

 <Canvas.DataContext>
  <ViewModels:VMSomeControl Model="{Binding RelativeSource={RelativeSource TemplatedParent}}" />
 </Canvas.DataContext>

 <!-- DataContext is not passed into these Instances.
      they also have no knowledge of their TemplatedParent. -->
 <Canvas.Resources>

  <!--  is there a way to use a binding that points to the datacontext within the resources ? -->
  <Converters:SomeConverter x:Key="someConverter" 
                            SomeProperty="{Binding Path=Model.SomeProperty}" />

  <!--  is there a way to point Directly to the TemplatedParent  ? -->
  <Converters:SomeConverter x:Key="someConverter" 
                            SomeProperty="{TemplateBinding SomeProperty}" />

 </Canvas.Resources>


 <SomeFrameworkElement SomeProperty="{Binding Path=Model.SomeOtherProperty, Converter={StaticResource someConverter}, ConverterParameter=0}" />

 <SomeFrameworkElement SomeProperty="{Binding Path=Model.SomeOtherProperty, Converter={StaticResource someConverter}, …
Run Code Online (Sandbox Code Playgroud)

wpf datacontext binding controltemplate ivalueconverter

5
推荐指数
2
解决办法
1万
查看次数

使用值转换器绑定到Silverlight 4中的FontWeight

我想比较各种属性的两个版本,如果它不等于另一个,则加粗其中一个.由于SL4不支持MultiBinding,我将FontWeight绑定到".".以便将整个数据上下文传递给转换器.然后,我使用converter参数指定要在转换器中比较的字段.到目前为止,这么好......不匹配的值是粗体.

问题是粗体属性绑定到可以编辑的文本框.编辑该值时,我希望"重新激活"转换器,以便根据值设置字体粗细.这不会发生.如何实现这一目标?

注意:我已经为相关的类和属性实现了INotifyPropertyChanged.更改值后切换到下一个字段会导致PropertyChanged事件触发,但在我实际移动到另一个记录然后返回到已更改的记录之前,字体权重不会更新.

(我也尝试使用Mode = TwoWay来查看是否可以解决问题.但是,当你绑定到"."时,不能使用TwoWay绑定.)

silverlight xaml binding ivalueconverter

5
推荐指数
1
解决办法
1551
查看次数