JohnChris JohnChris - 2 months ago 6
C# Question

Data Trigger and Binding not working

I am trying to bind for the first time with the aim for my C# code determining what colour xaml will make the text in a custom text box.

My C# Code:

public class Limits
{
public static bool fruitLimits(string textboxDec, ComboBox boxVariable)
{
if (string.IsNullorWhiteSpace(textboxDec)
{return false;}
else if (boxVariable.SelectedIndex == 1)
{
try
{ int apples = Convert.ToInt32(textboxDex);
if ( apples < 4 && apples != 0)
{return false;}
else if( apples > 50)
{return false;}
else
return true;
}
catch (FormatException fEx)
{return false;}
}
else
{
try
{ int oranges = Convert.ToInt32(textboxDec);
if (oranges < 1 && oranges != 0)
{
return false;}
else if (oranges > 100)
{return false;}
else
return true;
}
catch (FormatException fEx2)
{return false;}
}
}


So now I want to bind this method to XAML so when this method returns true, the text in the box is Black, when it returns false, the text is red.

<local:DigitBox x:Name="FruitNumber">
<local:DigitBox.Style>
<Style TargetType="local:DigitBox">
<Style.Triggers>
<DataTrigger
Binding="{Binding Limits.fruitLimits}" Value="False">
<Setter Property="Foreground" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</local:DigitBox.Style>
</local:DigitBox>


So no errors are found but my custom textbox does not change colour. I tried setting my colour changes directly in my c# method and that works. But I am trying to keep to what I have been reading which is keeping visual changes in xaml. This needs binding but I am obviously missing/not understanding something critical

Answer

Your problem is that you are trying to bind to a Methode instead of a property. Try something like this:

public static bool fruitLimits
{
    get
    { //here your methode code }
}

EDIT: There is no way to pass arguments into the Property, so if you don't have access to the values of the text box you may have to write a converter that gets these values passed. Here the basics: link You can pass one object as the value and the other as the parameter. The converter then processes the information and returns a bool.

Comments