I have the button below which has it's IsEnabled property bound to a bool in the ViewModel called EnableBtn.
If I have another bool called EnableMail how would I amend this so that the IsEnabled is bound to both?
<Button IsEnabled="{Binding EnableBtn, Converter={StaticResource InvertBooleanConverter}}" x:Name="SaveSendButton" Grid.Row="0" Grid.Column="1" Text="{i18n:Translate SaveAndSend}" Style="{StaticResource bottomButtonsBlue}" Command="{Binding EmailPlanCommand}"></Button>
public bool IsBothEnabled
{
get
{
if (EnableBtn && EnableMail)
return true;
return false;
}
}
Now bind your Button.IsEnabled Property to IsBothEnabled.
Alternative to the valid solution from meq, you could use a multi binding:
The XAML code would look like:
<Button.IsEnabled>
<MultiBinding Converter="{StaticResource AreAllTrueMultiValueConverter}">
<Binding Path="EnableBtn" />
<Binding Path="EnableMail" />
</MultiBinding>
</TextBox.IsEnabled>
However, you need a MultiValueConverter similar to:
public class AreAllTrueMultiValueConverter: IMultiValueConverter
{
public object Convert(object[] values, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
return values.OfType<bool>().All();
}
public object[] ConvertBack(object value, Type[] targetTypes,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException("Cannot convert back");
}
}
I would prefer the MultiBinding to the additional view model property because it doesn't require "dependent properties" that has to be notified if another property changed. Therefore it results in simpler view model logic.
Related
Is it possible to bind a TextBox Text field to a property TextView in my model with mode OneWay, and bind to another property TextInput with mode OneWayToSource?
ie. If I change the TextView property in code, the wpf control content changes. And if I type in the TextBox, the change is reflected in TextInput.
I agree it's not the right way to do this, but being able to do this would spare me a lot of work right now.
Is it possible to bind a TextBox Text field to a property TextView in my model with mode OneWay, and bind to another property TextInput with mode OneWayToSource?
No. You can only apply a single binding to a target property.
You could use a multi converter to convert the value of several properties into one target value though: https://blog.csainty.com/2009/12/wpf-multibinding-and.html.
Something like this:
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource MultiValueConverter}">
<Binding Path="TextView" />
<Binding Path="TextInput" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
public class NameMultiValueConverter : IMultiValueConverter
{
private string _textView;
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//display the value of TextView
_textView = values[0].ToString();
return _textView;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return new object[] { _textView, /* TextInput: */ value.ToString() };
}
}
Alternatively you could handle the conversion logic in the setter of your source property.
So I'm trying to build out a project that will allow a user to type some text into a textbox on the left side of the form and that will filter out the available items from my datasource list.
<Label Content="Enter item name below"></Label>
<TextBox Name="SearchTermTextBox" TabIndex="0" Text="" />
I was under the impression I could bind to the datasource the list then use a converter to filter out the items that were unlike the string.
<ListBox DataContext="{Binding Colors}">
<ListBox.ItemsSource>
<MultiBinding Converter="{StaticResource FilterTextValueConverter}" ConverterParameter="{Binding ElementName=SearchTermTextBox, Path=Text}" />
</ListBox.ItemsSource>
<ListBox.ItemTemplate>
//etc...
</ListBox.ItemTemplate>
</ListBox>
However, you can't bind to an elementname in the converterparameter unless you use something called a dependency property.
Edit: Seeing as I've created confusion with the code above, here's the converter I'm trying to bind:
public class FilterTextValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var trackedColors = value as List<Colors>;
if (trackedColors != null)
return (trackedColors).Where(item => item.ColorName.Contains(parameter.ToString())).ToList();
return null;
}
public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class Colors
{
public String ColorName;
public String Description;
}
What is wrong with my approach here? Clearly I'm angering the WPF gods since this is a fairly straightforward operation but I'm being denied it on principle. Any help would be appreciated.
Simple binding with converter will work here, no need for MultiBinding.
<ListBox ItemsSource="{Binding Path=Text, ElementName=SearchTermTextBox,
Converter="{StaticResource FilterTextValueConverter}">
......
</ListBox>
Assuming FilterTextValueConverter is implementing IValueConverter, you can access text from value passed to Convert method.
public class FilterTextValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
string text = value.ToString(); // TEXT for textBox can be accessed here.
return new List<string>(); // Return filtered list from here.
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return Binding.DoNothing;
}
}
UPDATE
In case you want to pass multiple bindings to converter, use IMultiValueConverter because ConverterParameter is not Dependency property, hence cannot be bound.
XAML
<ListBox DataContext="{Binding Colors}">
<ListBox.ItemsSource>
<MultiBinding Converter="{StaticResource FilterTextValueConverter}">
<Binding/>
<Binding ElementName="SearchTermTextBox" Path="Text"/>
</MultiBinding>
</ListBox.ItemsSource>
</ListBox>
Converter
public class FilterTextValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
var trackedColors = values[0] as List<Colors>;
if (trackedColors != null && !String.IsNullOrEmpty(values[1].ToString()))
return (trackedColors).Where(item =>
item.ColorName.Contains(values[1].ToString())).ToList();
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes,
object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
I continued looking into this issue well after the accepted answer was posted and working for me. What I discovered is that it's a fairly trivial task to wrap the control you're trying to get a new dependencyproperty out of to allow for proper binding.
I will not be accepting my own answer to this determined so much later, but this seems (in my amateur opinion) like a much more elegant solution than adding a converter despite being a bit more complex:
Note that this is for a new dependency on the caretindex property of a textbox, not for the original question on binding, but it just requires some smart renaming to get it working ;).
public class TextBoxDependencyWrapper : TextBox
{
public static readonly DependencyProperty CaretIndexProperty = DependencyProperty.Register(
"CaretIndex", typeof (int), typeof (TextBoxDependencyWrapper), new FrameworkPropertyMetadata(default(int), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, CaretIndexChanged ));
protected override void OnKeyUp(KeyEventArgs e) //Event that changes the property we're trying to track
{
base.OnKeyUp(e);
CaretIndex = base.CaretIndex;
}
protected override void OnKeyDown(KeyEventArgs e) //Event that changes the property we're trying to track
{
base.OnKeyDown(e);
CaretIndex = base.CaretIndex;
}
public new int CaretIndex
{
get { return (int) GetValue(CaretIndexProperty); }
set { SetValue(CaretIndexProperty, value); }
}
}
I have a button with binding which works fine, see below:
<Button x:Name="licenceFilterSet" Content="Search" Command="{Binding searchCommand}" CommandParameter="{Binding Path=Text, ElementName=licenseTextBox}" />
Now I have realized that I need yet another piece of information, so I need to send the value of a check-box as well.
I modified the VM like this:
<Button x:Name="licenceFilterSet" Content="Search" Command="{Binding licenseSearchCommand}">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource searchFilterConverter}">
<Binding Path="Text" ElementName="licenseTextBox" />
<Binding Path="IsEnabled" ElementName="regularExpressionCheckBox" />
</MultiBinding>
</Button.CommandParameter>
</Button>
Below is my multi-converter:
/// <summary>
/// Converter Used for combining license search textbox and checkbox
/// </summary>
public class SearchFilterConverter : IMultiValueConverter
{
public object Convert(object[] values)
{
return new Tuple<String, bool>((String)values[0], (bool)values[1]);
}
}
What am I doing wrong. I am getting the following error, (which is pointing to my MultiBinding-tag in XAML):
Cannot set MultiBinding because MultiValueConverter must be specified.
you have to implement IMultiConverter
public class SearchFilterConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return new Tuple<String, bool>((String)values[0], (bool)values[1]);;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
then create the resource in xaml
<Converter:SearchFilterConverter x:Key="searchFilterConverter" />
then it should work
<Button x:Name="licenceFilterSet" Content="Search" Command="{Binding licenseSearchCommand}">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource searchFilterConverter}">
<Binding Path="Text" ElementName="licenseTextBox" />
<Binding Path="IsEnabled" ElementName="regularExpressionCheckBox" />
</MultiBinding>
</Button.CommandParameter>
</Button>
I know this thread is old, but I've faced the same problem yesterday where everything was written correctly yet the WPF was still refusing to locate the converter. What helped me was assigning the converter in the following manner:
<MultiBinding Converter="{local:ButtonParametersMultiValueConverter}">
That solved the issue.
That is not the correct implementation of the IMultiValueConverter interface.
The correct one is:
public class SearchFilterConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
....
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
}
}
Reference here.
I am simply trying to bind two controls as command parameters and pass them into my command as an object[].
XAML:
<UserControl.Resources>
<C:MultiValueConverter x:Key="MultiParamConverter"></C:MultiValueConverter>
</UserControl.Resources>
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Button Name="Expander" Content="+" Width="25" Margin="4,0,4,0" Command="{Binding ExpanderCommand}">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource MultiParamConverter}">
<Binding ElementName="Content"/>
<Binding ElementName="Expander"/>
</MultiBinding>
</Button.CommandParameter>
</Button>
<Label FontWeight="Bold">GENERAL INFORMATION</Label>
</StackPanel>
<StackPanel Name="Content" Orientation="Vertical" Visibility="Collapsed">
<Label>Test</Label>
</StackPanel>
</StackPanel>
Command:
public ICommand ExpanderCommand
{
get
{
return new RelayCommand(delegate(object param)
{
var args = (object[])param;
var content = (UIElement)args[0];
var button = (Button)args[1];
content.Visibility = (content.Visibility == Visibility.Visible) ? Visibility.Collapsed : Visibility.Visible;
button.Content = (content.Visibility == Visibility.Visible) ? "-" : "+";
});
}
}
Converter:
public class MultiValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return values;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException("No two way conversion, one way binding only.");
}
}
Basically what is happening is that the binding seems to be working fine and the converter is returning an object[] containing the correct values, however when the command executes the param is an object[] containing the same number of elements except they are null.
Can someone please tell me why the values of the object[] parameter are being set to null?
Thanks,
Alex.
This'll do it:
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values.ToArray();
}
Take a look at this question for the explanation.
currently when I have to make an OR of two values on the IsEnabled property of a control I end using an invisible container control (I use a Border) and setting the IsEnabled of the control and the one of the container.
Is there a better approach? If not, what is the most lightweight control for doing this?
Thanks in advance.
If IsEnabled is set via binding, you may use MultiBinding in conjunction with a multi-value converter.
You can use a converter like this:
public class BooleanOrConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
foreach (object value in values)
{
if ((value is bool) && (bool)value == true)
{
return true;
}
}
return false;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException("BooleanOrConverter is a OneWay converter.");
}
}
And this is how you would use it:
<myConverters:BooleanOrConverter x:Key="BooleanOrConverter" />
...
<ComboBox Name="MyComboBox">
<ComboBox.IsEnabled>
<MultiBinding Converter="{StaticResource BooleanOrConverter}">
<Binding ElementName="SomeCheckBox" Path="IsChecked" />
<Binding ElementName="AnotherCheckbox" Path="IsChecked" />
</MultiBinding>
</ComboBox.IsEnabled>
</ComboBox>
Could use a MultiBinding with a converter which or's the values passed in.