两个数据绑定在同一个控件WPF中

时间:2016-09-24 12:50:57

标签: c# wpf

当我写" Admin"在文本框中我想更改其内容绑定到类别的标签的背面颜色,如下所示:

<Window.Resources>
    <local:TextToColorConverter x:Key="TextToColorConverterDataSource" d:IsDataSource="True"/>
    <local:Class1 x:Key="Class1DataSource" d:IsDataSource="True"/>
</Window.Resources>
<Grid DataContext="{Binding Source={StaticResource Class1DataSource}}">
    <Label x:Name="label" Content="{Binding FullName, Mode=OneWay}" Height="26.463" Margin="77.951,23.512,232.463,0" VerticalAlignment="Top" Background="{Binding Content, Converter={StaticResource TextToColorConverterDataSource},UpdateSourceTrigger=PropertyChanged}"/>
    <TextBox x:Name="textBox1" Height="29.878" Margin="77,80,200,0" TextWrapping="Wrap" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" HorizontalAlignment="Left"/>
</Grid>

正如我上面所说的标签内容绑定到类的属性也是文本框文本绑定到类属性。代码是:

class Class1 : INotifyPropertyChanged
    {

        #region Properties
        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged("Name");
                OnPropertyChanged("FullName");
            }
        }


        private string _fullname;
        public string FullName
        {
            get { return string.Format("{0}", _name); }
            set
            {
                _fullname = value;
                OnPropertyChanged("FullName");
            }
        }
        #endregion

        #region INotifyPropertyChanged Implementing
        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

    }

Label的背景绑定到另一个类,它将文本转换为颜色:

   public class TextToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value.ToString() == "Admin")
                return new SolidColorBrush(Colors.Yellow);
            else
                return value;
        }

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

标签内容数据绑定运行良好但背景数据绑定不起作用...(当我绑定到文本框的文本标签背景时工作但是我想知道我怎样才能这样做)

1 个答案:

答案 0 :(得分:1)

问题在于背景绑定

Background="{Binding Content, Converter= ...}"

如上所述,您将绑定到Grid的DataContext上的属性Content,该属性不存在。

您可以绑定到Grid的DataContext上的右侧属性:

Background="{Binding FullName, Converter= ...}"

或使用Content绑定到标签上的RelativeSource属性:

Background="{Binding Content, RelativeSource={RelativeSource Self}, Converter= ...}"