Alan Wayne
Alan Wayne

Reputation: 5384

How to connect a button click to a customcontrol in XAML?

Simple newbie question.

I have a button that currently executes "insert" code in the viewmodel:

 <Button Content="Insert" Grid.Column="3" Grid.Row="2" Height="75" 
               Command="{Binding Insert}" />

In the same user control, I have a customcontrol, CustomInkCanvas, defined as:

<wc:CustomInkCanvas x:Name="myInkCanvas"
                    Vocabulary="{Binding Vocabulary, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"
                    Text="{Binding Text, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" 
                    WordPad="{Binding WordPad, UpdateSourceTrigger=PropertyChanged, Mode=OneWayToSource}"
                    CloseCharacterPads ="{Binding CloseCharacterPads}"
                    EditWord ="{Binding EditWord}"                
                />

What I would like to do is add something along the lines of:

       FormatText = {Binding ??? ElementName=Insert ???} 

to the customcontrol xaml such that clicking on the Button will send a message to the customcontrol to reformat itself. Also this reformatting will need to be done BEFORE the "insert" method of the viewmodel which the button is connected to. Just to be clear, I need the click on the button to first tell the custominkcanvas to reformat before doing the activity in the viewmodel.

Can this be done in through the XAML and if so how?

Thanks in advance for any help with this. (If I have a strong point, XAML is not it!)

Upvotes: 0

Views: 177

Answers (1)

SWilko
SWilko

Reputation: 3612

You could do it with 2 properties one on the view model and one on the custom control

CustomInkCanvas.cs

public string FormatText
    {
        get { return (string)GetValue(FormatTextProperty); }
        set { SetValue(FormatTextProperty, value); }
    }

    // Using a DependencyProperty as the backing store for FormatText.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty FormatTextProperty =
        DependencyProperty.Register("FormatText", typeof(string),
        typeof(CustomInkCanvas), new PropertyMetadata(string.Empty));

In your ViewModel (class will need to implement INotifyPropertyChanged)

private string _updatedText = string.Empty;

    public string UpdatedText
    {
        get { return _updatedText ; }
        set
        {
            _updatedText = value;
            OnPropertyChnaged("UpdatedText");
        }
    }

then on your custom control

<wc:CustomInkCanvas x:Name="myInkCanvas"
  FormatText={Binding Path="UpdatedText"} />

in your command Insert

this.UpdatedText = "your text";
//your insert code

Upvotes: 1

Related Questions