Lucian Lucian - 3 months ago 12
C# Question

Notify a property change from an user control without a viewmodel

I have a UserControl that wraps an ActiveX control. This control is an editor that has both text and sound. (The text has been speech-recognized so that when you play the sound the correct word is highlighted).

Here is the code from the UserControl:

public partial class EditorWrapper : UserControl
{
private CdsEditorOverrides editorCtrl;

public TextWithSound TextSound
{
set
{
try
{
if(value.Text != null && value.Stream != null)
{
editorCtrl.LoadDocumentSetAsXmlString(value.Text);
editorCtrl.GetAudioPlayer().LoadAudioFromStream(new StreamWrapper(value.Stream));
editorCtrl.GetAudioPlayer().AudioStreamingComplete();
Debug.WriteLine("TextSound updated");
}

}
catch (Exception ex)
{
Debug.WriteLine("Error loading Text: " + ex.ToString());
//don't throw in get/set
}
}
}

public int SoundLength
{
get
{
return editorCtrl.GetAudioPlayer().GetPlaybackLength();
}
set { /* do nothing */ }
}


Here is the XAML code where I try to use it:

<editorWrapper:EditorWrapper
Name="editorObj"
TextSound="{Binding Dictation.TextWithSound}"
SoundLength="{Binding Dictation.SoundLengthInMilliseconds, Mode=OneWayToSource}"/>


I want to notify when the
TextSound
property is set that the
SoundLength
is also changed. How do I do that? Do I have to implement a ViewModel for this user-control or is there another way?

Answer

You could define the SoundLength property as a DependencyProperty.

Your UserControl would look like this:

public partial class EditorWrapper : UserControl
{
    // Your defined DependencyProperty
    public static readonly DependencyProperty SoundLengthProperty=DependencyProperty.Register("SoundLength",typeof(int),typeof(EditorWrapper),new PropertyMetadata(OnSoundLengthChanged));

    public TextWithSound TextSound
    {
        set
        {
            try
            {
                if(value.Text != null && value.Stream != null)
                {
                    CdsEditorOverrides editorCtrl.LoadDocumentSetAsXmlString(value.Text);
                    editorCtrl.GetAudioPlayer().LoadAudioFromStream(new StreamWrapper(value.Stream));
                    editorCtrl.GetAudioPlayer().AudioStreamingComplete();

                    // set the sound length (will automatically notify the binding)
                    SoundLength=editorCtrl.GetAudioPlayer().GetPlaybackLength();

                    Debug.WriteLine("TextSound updated");
                }

            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error loading Text: " + ex.ToString());
                //don't throw in get/set
            }
        }
    }

    // The actual Property: gets/sets the value to the DependencyProperty
    public int SoundLength
    {
        get { return (int)GetValue(SoundLengthProperty); }
        private set { SetValue(SoundLengthProperty,value); }
    }
}