Question

I have a UserControl that I'm writing that will have a TextBox and Button. When the user clicks the button, I'd like the current date/time to be placed into the TextBox. The code below has two issues:

  1. For some reason the binding is throwing an exception "Two-way binding requires Path or XPath".
  2. If I just set the value to something like "Test", then it works but only while the button itself is pressed, once I lift the mouse button the text goes away.

In essence, I'd like the value to be set at mouse click not during. I'd like to keep this pure xaml if possible, but I understand if it needs to be in the code-behind. Any help would be appreciated!

<Button x:Name="ClockGo">
    <Image Source="/Best.Controls;component/Resources/clock_go.png" />
</Button>
<TextBox HorizontalAlignment="Stretch">
    <TextBox.Style>
        <Style TargetType="TextBox">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=ClockGo, Path=IsPressed}" Value="True">
                    <Setter Property="Text" Value="{Binding Source={x:Static sys:DateTime.Today}, StringFormat='{}{0:MM/dd/yyyy}'}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>
Was it helpful?

Solution

You should be able to get rid of "Two-way binding requires Path or XPath" exception by setting the binding mode to OneWay. Textbox has a two way binding by default and I believe the exception is due to the value conversion.

<Setter Property="Text" Value="{Binding Source={x:Static sys:DateTime.Now}, StringFormat='{}{0:MM/dd/yyyy hh:mm:ss}', Mode=OneWay}" />

On your second point where the value only shown when the button is pressed and goes away after button click is released, this is the expected behaviour. The Trigger Setter only apply when the binding condition is true, it will be revert to default value when the condition no longer true.

Please refer to MSDN site on the remark section which spells out above behaviour: http://msdn.microsoft.com/en-us/library/system.windows.trigger.aspx

Unless you have a very strong reason to stick with XAML based solution, code behind seems to be the better option here instead of tweaking with triggers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top