Skip to main content

ferroui_xaml_interactivity/styled_element/
styled_element_behavior_of_t.rs

1//! Port of `StyledElement/StyledElementBehaviorOfT.cs` (`StyledElementBehavior<T>`).
2
3use crate::ferro_object::behavior_of_t::{associated_object_as, check_associated_type};
4use crate::{StyledElementBehavior, StyledElementBehaviorImpl, StyledElementBehaviorImplExt};
5use ferroui_base::{ferro_class, FerroObjectImpl, ObjectType, Ref, StyledElementImpl, TypeInfo};
6
7/// A base class for behaviors making them code compatible with older frameworks, and allow for
8/// typed associated objects (`StyledElementBehavior<T>`).
9///
10/// Deviation (DEVIATIONS.md, Behaviors): the type argument `T` of the reference is the runtime
11/// type a deriving class passes to [`construct`](Self::construct); see
12/// [`BehaviorOfT`](crate::BehaviorOfT).
13#[repr(C)]
14pub struct StyledElementBehaviorOfT {
15    base: StyledElementBehavior,
16    associated_type: &'static TypeInfo,
17}
18
19ferro_class!(StyledElementBehaviorOfT: StyledElementBehavior);
20ferroui_base::ferro_impl_classes!(StyledElementBehaviorOfT: FerroObjectImpl, StyledElementImpl);
21
22ferroui_base::ferro_overrides! {
23    impl StyledElementBehaviorImpl for StyledElementBehaviorOfT {
24        /// Called after the behavior is attached to the associated object: checks the type of the
25        /// associated object.
26        fn on_attached(this: &Self) {
27            Self::parent_on_attached(this);
28
29            check_associated_type(this.associated_object(), this.associated_type);
30        }
31    }
32}
33
34impl StyledElementBehaviorOfT {
35    /// Creates the class data for behaviors attached to objects of `associated_type` (the `T` of
36    /// the reference); see [`ferroui_base::FerroObject::construct`].
37    pub fn construct(associated_type: &'static TypeInfo) -> Self {
38        Self { base: StyledElementBehavior::construct(), associated_type }
39    }
40
41    /// The type of the objects the behavior attaches to (the `T` of the reference).
42    pub fn associated_type(&self) -> &'static TypeInfo {
43        self.associated_type
44    }
45
46    /// Gets the object to which this behavior is attached, as `T`.
47    pub fn associated_object_as<T: ObjectType>(&self) -> Option<Ref<T>> {
48        associated_object_as::<T>(self.associated_object())
49    }
50}