<Window.Resources>
<local:WeightConverter x:Key="weightConverter" RequiredUnit="{Binding VmProp}" />
<TextBlock Text="{Binding Weight, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource weightConverter}}" />
public MainWindow()
{
InitializeComponent();
DataContext = new MyViewModel();
在MyViewModel我有定期的財產
private string vmProp;
public string VmProp
{
get
{
return "kg";
}
}
和轉換器類有DependencyProperty的是:
public class WeightConverter : DependencyObject, IValueConverter
{
public static readonly DependencyProperty RequiredUnitProperty = DependencyProperty.Register("RequiredUnit", typeof(string), typeof(WeightConverter), null);
public string RequiredUnit
{
get
{
return (string)this.GetValue(RequiredUnitProperty);
}
set
{
this.SetValue(RequiredUnitProperty, value);
}
}
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double dblValue;
if (double.TryParse(value.ToString(), out dblValue))
{
if (this.RequiredUnit == "kg")
{
return dblValue;
}
else
{
return dblValue * 10;
}
return dblValue;
}
return 0;
}
當我做bi nding在XAML代碼工作:
<Window.Resources>
<local:WeightConverter x:Key="weightConverter" RequiredUnit="kg"/>
但是當我嘗試其綁定到ViewModelProperty的「RequiredUnit」對象始終是零。
如何將依賴項屬性綁定到ViewModel屬性?
你的綁定是的,你是對我有datacontext的問題。我做了兩種方法,但我仍然沒有解決問題。 – leapold