[英]How to simply bind this to ConverterParameter?
我有問題,我不知道如何解決這個簡單問題,我有很多觀點,那么解決方案應該不復雜。
我有帶有設置和主要XAML的主項目。
我有綁定轉換器和XAML文件的依賴項目,如下所示:
<TextBlock Text="{Binding X.Y.Z,
Converter={StaticResource ProbabilityConverter},
ConverterParameter=??????????????, Mode=OneWay}"
/>
該XAML文件由主項目中的主XAML文件加載。
我必須將一個屬性的值從Setting的值傳遞給ConverterParameter
,此參數可以在運行時更改,然后必須是Binding
,在這種情況下, Binding
只能對DependencyProperty
進行。
我必須對此Setting屬性進行DependencyProperty
包裝,以解決此問題嗎?
當我嘗試在ConverterParameter
設置Binding
,我將在運行時收到此異常:
不能在“綁定”類型的“ ConverterParameter”屬性上設置“綁定”。 只能在DependencyObject的DependencyProperty上設置“綁定”。
您可以綁定到任何屬性,它不必是依賴項屬性。 但是,如果希望用戶界面在發生更改時立即反映出屬性中的更改,則有兩個選擇:
INotifyPropertyChanged
,並在屬性更改時引發PropertyChanged
事件。 編輯:
如問題編輯所指出的,不可能綁定到ConverterParameter
。 但是您可以使用MultiBinding
。 例如,假設您要綁定日期,並指定轉換器的區域性規范作為參數,並在區域性更改時刷新綁定(我不確定這是個好主意,但可以很好地作為示例)。 您可以這樣做:
<TextBlock>
<TextBlock.Resources>
<local:DateCultureConverter x:Key="converter" />
</TextBlock.Resources>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource converter}">
<Binding Path="Date" />
<Binding Path="Settings.Culture" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
在這里, Date
和Settings
都是當前DataContext
屬性。 DateCultureConverter
實現IMultiValueConverter
,您可能會將其放在資源中,而不是實際應用程序中層次結構IMultiValueConverter
幾個級別。
您可以使用以下解決方案之一:
您必須集成類BindableParameter和BindableParameterExtension(如下所示),然后可以按以下方式使用它:
在XAML中:
xmlns:local="clr-namespace:BindableParameterExtension"
<local:SampleConverter x:Key="sampleConverter" />
<StackPanel Orientation="Vertical">
<TextBox Name="txtContent" Text="Text from txtContent" />
<TextBox Name="txtParameter" Text="Text from txtParameter" />
<TextBox Name="txtBindingSample"
Text="{Binding ElementName=txtContent, Path=Text, Converter={StaticResource sampleConverter}}"
local:BindableParameter.BindParameter="{local:BindableParameter TargetProperty=TextBox.Text,
Binding={Binding ElementName=txtParameter, Path=Text} }" />
</StackPanel>
屬性“ TargetProperty”:
TargetProperty=TextBox.Text
必須將BindableParamerter的設置為原始bound屬性(在本例中為“ TextBox.Text”)。
樣本轉換器:
using System;
using System.Windows.Data;
namespace BindableParameterExtension
{
public class SampleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null && parameter != null)
{
return value.ToString() + ", " + parameter.ToString();
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is string && parameter is string)
{
string text1 = value as string;
string textParamter = parameter as string;
return text1.Replace(textParamter, "");
}
return value;
}
}
}
該參數可以在“轉換”和“轉換后退”方法中使用(用於綁定到視圖模型)。
類BindableParameter和BindableParameterExtension(URL參見上文(不是我的代碼))
/*
* Copyright - Everyone can use this code for any reason yet if you find a bug, I do not hold myself responsable :D
*/
using System.Windows.Data;
using System.Windows.Markup;
namespace BindableParameterExtension
{
/// <summary>
/// BindableParameter is the class that changes the ConverterParameter Value
/// This must inherit from freezable so that it can be in the inheritance context and thus be able to use the DataContext and to specify ElementName binding as a ConverterParameter
/// http://www.drwpf.com/Blog/Default.aspx?tabid=36&EntryID=36
/// </summary>
public class BindableParameter : Freezable
{
#region fields
//this is a hack to trick the WPF platform in thining that the binding is not sealed yet and then change the value of the converter parameter
private static FieldInfo isSealedFieldInfo;
#endregion
#region Properties
#region Parameter
/// <summary>
/// Parameter Dependency Property
/// </summary>
public static readonly DependencyProperty ParameterProperty =
DependencyProperty.Register("Parameter", typeof(object), typeof(BindableParameter),
new FrameworkPropertyMetadata((object)null,
(d, e) =>
{
BindableParameter param = (BindableParameter)d;
//set the ConverterParameterValue before calling invalidate because the invalidate uses that value to sett the converter paramter
param.ConverterParameterValue = e.NewValue;
//update the converter parameter
InvalidateBinding(param);
}
));
/// <summary>
/// Gets or sets the Parameter property. This dependency property
/// indicates ....
/// </summary>
public object Parameter
{
get { return (object)GetValue(ParameterProperty); }
set { SetValue(ParameterProperty, value); }
}
#endregion
#region BindParameter
/// <summary>
/// BindParameter Attached Dependency Property
/// </summary>
public static readonly DependencyProperty BindParameterProperty =
DependencyProperty.RegisterAttached("BindParameter", typeof(BindableParameter), typeof(BindableParameter),
new FrameworkPropertyMetadata((BindableParameter)null,
new PropertyChangedCallback(OnBindParameterChanged)));
/// <summary>
/// Gets the BindParameter property. This dependency property
/// indicates ....
/// </summary>
public static BindableParameter GetBindParameter(DependencyObject d)
{
return (BindableParameter)d.GetValue(BindParameterProperty);
}
/// <summary>
/// Sets the BindParameter property. This dependency property
/// indicates ....
/// </summary>
public static void SetBindParameter(DependencyObject d, BindableParameter value)
{
d.SetValue(BindParameterProperty, value);
}
/// <summary>
/// Handles changes to the BindParameter property.
/// </summary>
private static void OnBindParameterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = d as FrameworkElement;
if (element == null)
throw new InvalidOperationException("BindableParameter can be applied to a FrameworkElement only");
BindableParameter parameter = (BindableParameter)e.NewValue;
element.Initialized += delegate
{
parameter.TargetExpression = BindingOperations.GetBindingExpression(element, parameter.TargetProperty);
parameter.TargetBinding = BindingOperations.GetBinding(element, parameter.TargetProperty);
//update the converter parameter
InvalidateBinding(parameter);
};
}
#endregion
public object ConverterParameterValue { get; set; }
public BindingExpression TargetExpression { get; set; }
public Binding TargetBinding { get; private set; }
/// <summary>
/// Gets the object being bound
/// </summary>
public DependencyObject TargetObject { get; private set; }
/// <summary>
/// Gets the dependency property being bound
/// </summary>
public DependencyProperty TargetProperty { get; internal set; }
#endregion
/// <summary>
/// Static constructor to get the FieldInfo meta data for the _isSealed field of the BindingBase class
/// </summary>
static BindableParameter()
{
//initialize the field info once
isSealedFieldInfo =
typeof(BindingBase).GetField("_isSealed", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (isSealedFieldInfo == null)
throw new InvalidOperationException("Oops, we have a problem, it seems like the WPF team decided to change the name of the _isSealed field of the BindingBase class.");
}
private static void InvalidateBinding(BindableParameter param)
{
if (param.TargetBinding != null && param.TargetExpression != null)
{
//this is a hack to trick the WPF platform in thining that the binding is not sealed yet and then change the value of the converter parameter
bool isSealed = (bool)isSealedFieldInfo.GetValue(param.TargetBinding);
if (isSealed)//change the is sealed value
isSealedFieldInfo.SetValue(param.TargetBinding, false);
param.TargetBinding.ConverterParameter = param.ConverterParameterValue;
if (isSealed)//put the is sealed value back as it was...
isSealedFieldInfo.SetValue(param.TargetBinding, true);
//force an update to the binding
param.TargetExpression.UpdateTarget();
}
}
#region Freezable Stuff
protected override Freezable CreateInstanceCore()
{
//throw new NotImplementedException();
//return _bindableParam;
return this;
}
#endregion
}
/// <summary>
/// Markup extension so that it is easier to create an instance of the BindableParameter from XAML
/// </summary>
[MarkupExtensionReturnType(typeof(BindableParameter))]
public class BindableParameterExtension : MarkupExtension
{
/// <summary>
/// Gets or sets the Dependency property you want to change the binding's ConverterParameter
/// </summary>
public DependencyProperty TargetProperty { get; set; }
/// <summary>
/// Gets or sets the Binding that you want to use for the converter parameter
/// </summary>
public Binding Binding { get; set; }
/// <summary>
/// constructor that accepts a Dependency Property so that you do not need to specify TargetProperty
/// </summary>
/// <param name="property">The Dependency property you want to change the binding's ConverterParameter</param>
public BindableParameterExtension(DependencyProperty property)
{
TargetProperty = property;
}
public BindableParameterExtension()
{ }
public override object ProvideValue(IServiceProvider serviceProvider)
{
_bindableParam = new BindableParameter();
//set the binding of the parameter
BindingOperations.SetBinding(_bindableParam, BindableParameter.ParameterProperty, Binding);
_bindableParam.TargetProperty = TargetProperty;
return _bindableParam;
}
private BindableParameter _bindableParam;
}
}
您必須集成ObjectReference類:
http://www.drwpf.com/blog/Portals/0/Code/ObjectReference.cs.txt
在XAML中:
xmlns:local="clr-namespace:WpfMarkupExtension"
<local:SampleConverter x:Key="sampleConverter" />
<StackPanel Orientation="Vertical">
<TextBox Name="txtContent" Text="Text from txtContent" />
<TextBox Name="txtParameter" Text="Text from txtParameter" local:ObjectReference.Declaration="{local:ObjectReference txtParam}" />
<TextBox Name="txtBindingSample"
Text="{Binding ElementName=txtContent, Path=Text,
Converter={StaticResource sampleConverter},
ConverterParameter={local:ObjectReference txtParam}}" />
</StackPanel>
片段:
local:ObjectReference.Declaration="{local:ObjectReference txtParam}"
在靜態字典和零件中創建引用:
ConverterParameter={local:ObjectReference txtParam}}"
從字典中獲取此對象引用->這里沒有綁定,字典將在解析時填充。
樣本轉換器:
using System;
using System.Windows.Controls;
using System.Windows.Data;
namespace WpfMarkupExtension
{
public class SampleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null && parameter is TextBox)
{
return value.ToString() + ", " + ((TextBox)parameter).Text;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is string && parameter is TextBox)
{
string text1 = value as string;
string textParamter = ((TextBox)parameter).Text;
return text1.Replace(textParamter, "");
}
return value;
}
}
}
http://www.codeproject.com/Articles/456589/Bindable-Converter-Parameter
在XAML中:
xmlns:local="clr-namespace:BcpBindingExtension"
<local:SampleConverter x:Key="sampleConverter" />
<StackPanel Orientation="Vertical">
<TextBox Name="txtContent" Text="Text from txtContent" />
<TextBox Name="txtParameter" Text="Text from txtParameter" />
<TextBox Name="txtBindingSample">
<TextBox.Text>
<local:BcpBinding Path="Text" ElementName="txtContent"
Converter="{StaticResource sampleConverter}"
ConverterParameters="Binding Path=Text ElementName=txtParameter"
Mode="TwoWay"/>
</TextBox.Text>
</TextBox>
</StackPanel>
樣本轉換器:
using System;
using System.Windows.Data;
namespace BcpBindingExtension
{
public class SampleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null && parameter is object[] && ((object[])parameter).Length > 0)
{
return value.ToString() + ", " + ((object[])parameter)[0].ToString();
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is string && parameter is object[] && ((object[])parameter).Length > 0)
{
string text1 = value as string;
string textParamter = ((object[])parameter)[0] as string;
return text1.Replace(textParamter, "");
}
return value;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.